Skip to content

Commit

Permalink
fix: profile image upload
Browse files Browse the repository at this point in the history
  • Loading branch information
AdelakunShola committed Aug 6, 2024
1 parent a812cbe commit f20ecae
Showing 1 changed file with 28 additions and 48 deletions.
76 changes: 28 additions & 48 deletions app/Http/Controllers/Api/V1/User/ProfileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;


class ProfileController extends Controller
Expand Down Expand Up @@ -100,6 +101,7 @@ public function update(Request $request)

public function uploadImage(Request $request)
{

$validator = Validator::make($request->all(), [
'file' => 'required|image|mimes:jpeg,png,jpg,gif'
]);
Expand All @@ -111,62 +113,40 @@ public function uploadImage(Request $request)
], 400);
}


$file = $request->file('file');
$imagePath = $file->getRealPath();

$cloudinaryCloudName = env('CLOUDINARY_CLOUD_NAME');
$cloudinaryUploadPreset = env('CLOUDINARY_UPLOAD_PRESET');

if (!$cloudinaryCloudName || !$cloudinaryUploadPreset) {
return response()->json([
'Status' => 500,
'Message' => 'Cloudinary environment variables are not set correctly'
], 500);
$fileName = time() . '.' . $file->getClientOriginalExtension();
$filePath = public_path('uploads');


if (!File::exists($filePath)) {
File::makeDirectory($filePath, 0755, true);
}

try {

$response = Http::asMultipart()->post('https://api.cloudinary.com/v1_1/' . $cloudinaryCloudName . '/image/upload', [
'file' => fopen($imagePath, 'r'),
'upload_preset' => $cloudinaryUploadPreset,
]);

$data = $response->json();

$file->move($filePath, $fileName);

if ($response->successful()) {
$uploadedFileUrl = $data['secure_url'];

$imageUrl = url('uploads/' . $fileName);

$user = Auth::user();
$profile = $user->profile;

if (!$profile) {
return response()->json([
'Status' => 404,
'Message' => 'Profile not found'
], 404);
}

$profile->update(['avatar_url' => $uploadedFileUrl]);

$user = Auth::user();
$profile = $user->profile;

return response()->json([
'Status' => 200,
'Message' => 'Image uploaded and profile updated successfully',
'Data' => ['avatar_url' => $uploadedFileUrl]
], 200);
} else {
return response()->json([
'Status' => 500,
'Message' => 'Failed to upload image to Cloudinary',
'CloudinaryResponse' => $data
], 500);
}
} catch (\Exception $e) {
if (!$profile) {
return response()->json([
'Status' => 500,
'Message' => 'Failed to upload image',
'Error' => $e->getMessage()
], 500);
'Status' => 404,
'Message' => 'Profile not found'
], 404);
}

$profile->update(['avatar_url' => $imageUrl]);

return response()->json([
'Status' => 200,
'Message' => 'Image uploaded and profile updated successfully',
'Data' => ['avatar_url' => $imageUrl]
], 200);
}


Expand Down

0 comments on commit f20ecae

Please sign in to comment.