Laravel - Create User REST API

Laravel - Create User REST API

[0] Prep

Continue from previous article or download quickstart file.

Laravel v.10

Breeze v.1.28

[1] Create User REST API

Create API controller for user:

php artisan make:controller API/UserController --api

Add new routes for UserController API:

(file: C:\laragon\www\larabreeze\routes\api.php )

use App\Http\Controllers\API\UserController;
Route::get('/users', [UserController::class, 'index']);
Route::post('/users/register', [UserController::class, 'register']);
Route::post('/users/login', [UserController::class, 'login']);
Route::post('/users/me', [UserController::class, 'me'])->middleware('auth:sanctum');

Put some test codes:

(file: C:\laragon\www\larabreeze\app\Http\Controllers\REST\UserController.php )

<?php

namespace App\Http\Controllers\REST;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;


class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): JsonResponse
    {
        return response()->json(['message' => 'index test'], 200);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        return response()->json(['message' => 'store test'], 200);        
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}

Outcome:

GET

POST

Add register function to process user registration:

    public function register(Request $request): JsonResponse
    {

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', \Illuminate\Validation\Rules\Password::defaults()],
        ]);

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

        event(new Registered($user));

        return response()->json([
            'message' => 'User created successfully. Check email for verfication.'],
            201);

    }

Add login function to process user login:

    public function login(Request $request): JsonResponse
    {
        $credentials = $request->only('email', 'password');

        if (!Auth::attempt($credentials)) {
            return response()->json([
                'user' => null,
                'message' => 'Invalid login details',
                'status' => 'failed',
            ], 200);
        }

        $user = User::where("email", $request["email"])->firstOrFail();

        $user_out = [
            'id' => $user->id,
            'email' => $user->email,
            'email_verified_at' => $user->email_verified_at,
            'status' => 'loggedin',
        ];

        if ($user->email_verified_at !== null) {
            $token = $user->createToken('auth_token')->plainTextToken;
            $user_out['user_token'] = $token;
            $user_out['token_type'] = 'Bearer';
            $user_out['verified'] = true;
        } else {
            $user_out['verified'] = false;
        }

        return response()->json($user_out, 200);
    }

Add me function to check a token:

    public function me(Request $request): JsonResponse
    {
        return response()->json($request->user(), 200);
    }

Test user registration using Postman:

Test user login using Postman:

(note: name is optional)

status is loggedin but verified is false.

Check mailbox:

Test login again:

Check the user_token: