Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions app/Http/API/V1/PersonalCabinetController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

namespace App\Http\API\V1;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Contracts\Auth\Authenticatable;

class PersonalCabinetController extends Controller
{
/**
* Получить данные пользователя
*
* @param Authenticatable $user Авторизованный пользователь
* @return \Illuminate\Http\JsonResponse
*/
public function index(Authenticatable $user)
{
$user = $user->load('profile');

return response()->json([
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сериализация отдана на откуп элоквент. он конечно выдаст в соответствии с полями в базе. Но это делает ваш код хрупким, потому что формат выдачи API зависит от структуры базы неявно.

'user' => $user,
'profile' => $user->profile,
]);
}

/**
* Обновить профиль пользователя
*
* @param Request $request
* @param User $user Авторизованный пользователь
* @return \Illuminate\Http\JsonResponse
*/
public function update(Request $request, Authenticatable $user)
{
$validator = Validator::make($request->all(), [
'name' => 'sometimes|string|max:255',
'email' => 'sometimes|string|email|max:255|unique:users,email,' . $user->id,
'phone' => 'nullable|string|max:20',
'address' => 'nullable|string|max:255',
'birth_date' => 'nullable|date',
'about' => 'nullable|string',
]);

if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}

// Обновляем основные данные пользователя
if ($request->has('name')) {
$user->name = $request->name;
}

if ($request->has('email')) {
$user->email = $request->email;
}

$user->save();

// Обновляем или создаем профиль
$profileData = $request->only(['phone', 'address', 'birth_date', 'about']);

if ($user->profile) {
$user->profile->update($profileData);
} else {
$profileData['user_id'] = $user->id;
UserProfile::create($profileData);
}

return response()->json([
'message' => 'Profile updated successfully',
'user' => $user->load('profile'),
]);
}

/**
* Удалить аккаунт пользователя
*
* @param User $user Авторизованный пользователь
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этого параметра в фукнции нет

* @return \Illuminate\Http\JsonResponse
*/
public function destroy()
{
// Получаем аутентифицированного пользователя
$user = auth('jwt')->user();

if ($user) {
$user->delete();
}

return response()->json([
'message' => 'Account deleted successfully',
]);
}
}
5 changes: 5 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,9 @@ public function getJWTCustomClaims(): array
'name' => $this->name,
];
}

public function profile()
{
return $this->hasOne(UserProfile::class);
}
}
52 changes: 52 additions & 0 deletions app/Models/UserProfile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
* App\Models\UserProfile
*
* @property int $id
* @property int $user_id
* @property string|null $phone
* @property string|null $address
* @property \Illuminate\Support\Carbon|null $birth_date
* @property string|null $about
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\Models\User $user
*
* @method static \Database\Factories\UserProfileFactory factory(...$parameters)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile query()
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereAbout($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereAddress($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereBirthDate($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile wherePhone($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserProfile whereUserId($value)
*
* @mixin \Eloquent
*/
class UserProfile extends Model
{
use HasFactory;

protected $fillable = [
'user_id',
'phone',
'address',
'birth_date',
'about',
];

public function user()
{
return $this->belongsTo(User::class);
}
}
8 changes: 7 additions & 1 deletion client.http
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@host = http://localhost
@token = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0L2FwaS9hdXRoL3JlZnJlc2gtdG9rZW4iLCJpYXQiOjE3NTUwNjY1NDAsImV4cCI6MTc1NTA2NzQ0MCwibmJmIjoxNzU1MDY2NTQwLCJqdGkiOiJRdzYxSUFlaUp3b0tIY1E5Iiwic3ViIjoiMSIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjciLCJyb2xlcyI6WzFdLCJlbWFpbCI6ImFkbWluQGV4YW1wbGUuY29tIiwibmFtZSI6IkFkbWluIFVzZXIifQ.AVplZoXXVmLGlapJMY17RNnUcqw5PH0vxtd1vu0yWWIcYM5WAFQ8sgFlrMH0sqaafMGTkikBTfyLGow6M2JxyS2xiCveMN6vxaBA_XwNUqASL4pIKDhkplB7rfxZO_vUxhMdT_0Qup6UQzAhRohq8-EWT6Ha9AjyOGXYSxWhAL1tGAUNLlAlk3Scsh5Zw4rkJRDhOx-OXPZFN3QxKO011Rc2uCzpeNS0j7Ij8zYw3KYO8ypLbPsajV6P1fIAso-Sn1rJ4jmITQnpHVPCPUkNh2O4Yc19KLOVx3W75PD59uaRCCod9mIkspBRJhlHwtlBi9p3q-9Q3Y3ePCbbhKLkVnEiWQj5sZ8L1z4pTi_syULBp6Fs9YCIGXZ8NbSXZUuyKjWCIw1w4XpUvM7W0RR8UdxNW8nzAWEaeE2WoPhGe7ZI0nqZte8oZUP2xCijCbQ8pqchHgAmuV9GsJjnGPN78kpv-xwAaJZpLxzXRRtM1lVYHUexsTiz6OV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-beVG87NF6GuKK13tAQzY5d_870WMU9byChw8UtXO_XE9P5nQIYO7oA7IAJKG8B-2022LroB7VNU9ssIZQ7vza1Q5plYFZdC0zgWFd6v-Ux359jN848fMWB2LGQs1CZG2WXN1EWRQReEl8TUUvc314t9XCiKObtTn8

### User login
POST {{host}}/api/auth/login
Expand All @@ -20,6 +20,12 @@ Content-Type: application/json
"refresh_token": "QzRYhsjlnlFuEWjKTqicvVufJplCneM9ddDppPkSsE5co1Kcote785iiKIlBwlWm"
}

### User profile
GET {{host}}/api/v1/personal-cabinet
Accept: application/json
Content-Type: application/json
Authorization: Bearer {{token}}

### Get all products (paginated)
GET {{host}}/api/v1/products
Authorization: Bearer {{token}}
Expand Down
Loading