DEV Community

John Maths
John Maths

Posted 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: ```bash

php artisan migrate


### Step 4: Create Authentication Endpoints
Laravel Breeze provides the necessary endpoints for registration, login, and logout. The routes are defined in routes/api.php.


```bash


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'],
]);

    <span class="k">if</span> <span class="o">(!</span>Auth::attempt<span class="o">(</span><span class="nv">$request</span>-&gt;only<span class="o">(</span><span class="s1">'email'</span>, <span class="s1">'password'</span><span class="o">)))</span> <span class="o">{</span>
        <span class="k">return </span>response<span class="o">()</span>-&gt;json<span class="o">([</span><span class="s1">'message'</span> <span class="o">=&gt;</span> <span class="s1">'Invalid login credentials'</span><span class="o">]</span>, 401<span class="o">)</span><span class="p">;</span>
    <span class="o">}</span>

    <span class="nv">$user</span> <span class="o">=</span> Auth::user<span class="o">()</span><span class="p">;</span>
    <span class="nv">$token</span> <span class="o">=</span> <span class="nv">$user</span>-&gt;createToken<span class="o">(</span><span class="s1">'auth_token'</span><span class="o">)</span>-&gt;plainTextToken<span class="p">;</span>

    <span class="k">return </span>response<span class="o">()</span>-&gt;json<span class="o">([</span>
        <span class="s1">'access_token'</span> <span class="o">=&gt;</span> <span class="nv">$token</span>,
        <span class="s1">'token_type'</span> <span class="o">=&gt;</span> <span class="s1">'Bearer'</span>,
        <span class="s1">'user'</span> <span class="o">=&gt;</span> <span class="nv">$user</span>,
        <span class="s1">'status'</span> <span class="o">=&gt;</span> <span class="s1">'Login successful'</span>,
    <span class="o">])</span><span class="p">;</span>
<span class="o">}</span>

public <span class="k">function </span>destroy<span class="o">(</span>Request <span class="nv">$request</span><span class="o">)</span>
<span class="o">{</span>
    <span class="nv">$request</span>-&gt;user<span class="o">()</span>-&gt;currentAccessToken<span class="o">()</span>-&gt;delete<span class="o">()</span><span class="p">;</span>

    <span class="k">return </span>response<span class="o">()</span>-&gt;json<span class="o">([</span><span class="s1">'message'</span> <span class="o">=&gt;</span> <span class="s1">'Logout successful'</span><span class="o">])</span><span class="p">;</span>
<span class="o">}</span>
Enter fullscreen mode Exit fullscreen mode

}

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