Laravel - Create User Profile Update API

[1] Open the Laravel Project

Continue from the previous tutorial https://hashnotes.hashnode.dev/laravel-create-user-register-api

[2] Edit ProfileController

(file: app\Http\Controllers\Api\ProfileController.php)

The controller has been created in the previous tutorial i.e. https://hashnotes.hashnode.dev/laravel-create-sanctum-token-for-user-login-api

Otherwise, you can create the controller now by running the following artisan command: php artisan make:controller Api/ProfileController

Add two functions:

  • edit(Request $request)

  • update(ProfileUpdateRequest $request)

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests\ProfileUpdateRequest;

class ProfileController extends Controller
{
    public function edit(Request $request)
    {
        $user=$request->user();
        return response()->json(
            [
                "user" => $user,
                "message" => "edit",
                "stus" => "ok",
            ],
            200
        );
    }

    public function update(ProfileUpdateRequest $request)
    {
        $request->user()->fill($request->validated());

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        $updated_user=$request->user()->save();

        return response()->json(
            [
                "user" => $updated_user,
                "message" => "update",
                "stus" => "ok",
            ],
            200
        );
    }


}

[4] Update API Routes

(file: routes\api.php )

use App\Http\Controllers\Api\ProfileController;
Route::middleware('auth:sanctum')->get('/profile/edit',[ProfileController::class, 'edit']);
Route::middleware('auth:sanctum')->post('/profile/update',[ProfileController::class, 'update']);

[5] Test API

[5.1] Send CURL (PowerShell) request to get data for editing:

curl --location 'http://localhost/rearnet/public/api/profile/edit' `
--header 'Accept: application/json' `
--header 'Authorization: Bearer 3|xYvJoZLf6I26ajekG4qZ9POXrhMMh6X2yhgmCL3Q12f42063'

[5.2] Send CURL (PowerShell) request to update data:

curl --location 'http://localhost/rearnet/public/api/profile/update' `
--header 'Accept: application/json' `
--header 'Authorization: Bearer 3|xYvJoZLf6I26ajekG4qZ9POXrhMMh6X2yhgmCL3Q12f42063' `
--form '_method="POST"' `
--form 'name="adam"' `
--form 'email="adam@razzi.my"' `
--form 'mobile="019"' `
--form 'gender="m"'