Laravel - Create User Register API

[1] Open the Laravel Project

Continue from the previous tutorial https://hashnotes.hashnode.dev/laravel-create-sanctum-token-for-user-login-api

[1.1] Optional: Reset database

You may want to reset your database so that you can reenter again your email for testing the registration api.

Open the console.

(for windows console, remove "../" from the sqlite database)

Run artisan command.

php artisan migrate:fresh

(for windows console, restore "../" in the sqlite database)

[2] Edit AuthController

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

Add the following header statements:

use Illuminate\Validation\Rules;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;

Add the code for registration process:

    public function register(Request $request): JsonResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

        $created_user= User::where('email', '=', $request->email)->first();

        return response()->json([
            'user'=>$created_user,
            'stus'=>'registered',
            'verified'=>false], 200);  
    }

[3] Edit API Route

(file: routes\api.php)

Add the following codes:

Route::post('register', [AuthController::class, 'register'])
    ->name('apiregister');

[4] Test

CURL command (using PowerShell console):

curl --location 'http://localhost/rearnet/public/api/register' `
--header 'Accept: application/json' `
--form '_method="POST"' `
--form 'name="bibi"' `
--form 'email="bibi@razzi.my"' `
--form 'password="aaaaaaaa"' `
--form 'password_confirmation="aaaaaaaa"'

A successful registration would receive the following response:

{"user":{"id":1,"name":"beta","email":"bibi@razzi.my","email_verified_at":null,"created_at":"2024-02-19T00:08:44.000000Z","updated_at":"2024-02-19T00:08:44.000000Z","gender":null,"mobile":null},"stus":"registered","verified":false}

Check the mailbox to click the email verification link.