DEV Community

John Maths
John Maths

Posted on • Edited on

How to Build an API with Laravel Breeze in Laravel 11

How to Build an API with Laravel Breeze in Laravel 11

A step-by-step guide on building a simple API with authentication using Laravel Breeze in Laravel 11.

Step 1: Install Laravel

First, create a new Laravel project using the Laravel installer or Composer.

laravel new api-breeze
# Or via Composer
composer create-project laravel/laravel api-breeze
cd api-breeze
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Laravel Breeze

Next, install Laravel Breeze and its dependencies.

composer require laravel/breeze --dev
php artisan breeze:install api
Enter fullscreen mode Exit fullscreen mode

This command will install Breeze and set up the necessary scaffolding for API authentication.

Step 3: Configure the Database and Run Migrations

  1. Update your .env file with your database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel11_api
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode
  1. Run the migrations to set up your database tables:
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Authentication Endpoints

Laravel Breeze provides the necessary endpoints for registration, login, and logout. The routes are defined in routes/api.php.

use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\RegisteredUserController;
use Illuminate\Support\Facades\Route;

Route::post('/register', [RegisteredUserController::class, 'store']);
Route::post('/login', [AuthenticatedSessionController::class, 'store']);
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])->middleware('auth:sanctum');
Enter fullscreen mode Exit fullscreen mode

Step 5: Update Controllers

Modify the RegisteredUserController and AuthenticatedSessionController to return JSON responses.

RegisteredUserController.php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use App\Http\Controllers\Controller;

class RegisteredUserController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

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

        event(new Registered($user));

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => $user
        ]);
    }
}

Enter fullscreen mode Exit fullscreen mode

AuthenticatedSessionController.php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthenticatedSessionController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ]);

        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['message' => 'Invalid login credentials'], 401);
        }

        $user = Auth::user();
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => $user,
            'status' => 'Login successful',
        ]);
    }

    public function destroy(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Logout successful']);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Run Laravel App

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Step 6: Check following API

Test Your API with Thunder Client

Register

Login

Top comments (1)

Collapse
 
geekmaros profile image
Mustapha Abdul-Rasaq

Super helpful thanks a bunch