Backend Profile - shibotsu/obs-clone GitHub Wiki
🧑💻 Profile Management
This document explains how the profile system works in the backend, including database structure and API routes.
📋 Overview
Profile management is used to fetch data about a specific user and to change the profile picture.
🗃️ Database Structure
📄 Users
A profile_picture
column is added to the users
table. It stores the path to the picture. Pictures are stored in the storage
directory, under the public
folder.
Column:
profile_picture
(String): Path to the user's profile picture.
Model Structure
Add profile_picture
to the fillable
array.
protected $fillable = [
'profile_picture',
];
🔗 API Endpoints
All the routes are protected with the auth:api
guard.
api.php
)
API Routes (Route::middleware('auth:api')->get('/profile', [ProfileController::class, 'show']);
Route::middleware('auth:api')->post('/picture', [ProfileController::class, 'changePicture']);
Route::get('/profile/{id}', [ProfileController::class, 'channel']);
GET /api/profile
Fetches the authenticated user's profile and retrieves the URL to the user's profile picture.
public function show(Request $request)
{
$user = $request->user();
if (!$user) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$userData = $user->toArray();
$userData['profile_picture'] = $user->profile_picture
? asset('storage/' . $user->profile_picture)
: null;
return response()->json($userData);
}
POST /api/picture
Updates the authenticated user's profile picture and returns the URL.
public function changePicture(Request $request)
{
$request->validate([
'profile_picture' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$user = auth()->user();
if (!$user) {
return response()->json(['error' => 'Unauthorized'], 401);
}
if ($user->profile_picture && Storage::disk('public')->exists($user->profile_picture)) {
Storage::disk('public')->delete($user->profile_picture);
}
$path = $request->file('profile_picture')->store('profile_pictures', 'public');
$user->profile_picture = $path;
$user->save();
return response()->json([
'message' => 'Profile picture updated successfully!',
'url' => asset('storage/' . $path),
]);
}
GET /api/profile/{id}
Fetches the specified user's profile (channel).
public function channel($id)
{
$channel = User::find($id);
if (!$channel) {
return response()->json(['error' => 'Channel does not exist'], 404);
}
$channelData = $channel->only(['username', 'number_of_followers', 'profile_picture']);
$channelData['profile_picture'] = $channel->profile_picture
? asset('storage/' . $channel->profile_picture)
: null;
return response()->json(['channel' => $channelData]);
}
🛠️ Additional Notes
If there are any problems with storage, try running this in the terminal:
php artisan storage:link