How to Build an API with Laravel Breeze in Laravel 11
Tags: laravel, php, api, tutorial
Published: 2024-07-12 15:10:22

---
title: "How to Build an API with Laravel Breeze in Laravel 11"
published: true
description: "A step-by-step guide on building a simple API with authentication using Laravel Breeze in Laravel 11."
tags: [laravel, php, api, tutorial]
---

## 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.

```bash
laravel new api-breeze
# Or via Composer
composer create-project laravel/laravel api-breeze
cd api-breeze
``` 

### Step 2: Install Laravel Breeze

Next, install Laravel Breeze and its dependencies.

```bash
composer require laravel/breeze --dev
php artisan breeze:install api
``` 
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:

```bash
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel11_api
DB_USERNAME=root
DB_PASSWORD=
``` 
2. 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');
``` 
### Step 5: Update Controllers
Modify the `RegisteredUserController` and `AuthenticatedSessionController` to return JSON responses.

`RegisteredUserController.php`
```bash
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
        ]);
    }
}

``` 

`AuthenticatedSessionController.php`

```bash
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']);
    }
}
```
### Step 5: Run Laravel App
```bash
php artisan serve
```

### Step 6: Check following API
Test Your API with Thunder Client

![Register](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mno0qxb10zndz15g5c6q.png)


![Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqxljuhb69ngrvzzgbe1.png)