Skip links

Creating REST API’s with Laravel Sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.

Note: All API endpoints should be written in routes/api.php folder.

Further to access any api endpoints, you need to add /api at the end of your base url. For eg: if your website address is example.com, and you created a route /v1/login, to call that route the url will be example.com/api/v1/login

Base url: example.com

API Endpoint: /v1/login

API Request: example.com/api/v1/login

Installing Sanctum to a Laravel project

composer require laravel/sanctum

// publish sanctum configurations and migrations
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

// migrate new migrations created with sanctum 
php artisan migrate

If you are planning to use Sanctum for authentication on your Application, you need to add sanctum’s middleware to your api middleware group in app/Http/Kernel.php file.

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

To begin issuing tokens for users, your User model should use the Laravel\Sanctum\HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Creating Laravel Login Route with Sanctum & Issuing token

Route::post('/v1/login', function (Request $request) {
    if (!Auth::attempt($request->only('email', 'password'))) {
        return response()->json([
        'message' => 'Invalid login details'
                   ], 401);
               }
        
        $user = User::where('email', $request['email'])->firstOrFail();
        
        $token = $user->createToken('auth_token')->plainTextToken;
        
        return response()->json([
                   'access_token' => $token,
                   'token_type' => 'Bearer',
                   'email => $user->email
        ]);
    
});

Creating Laravel Register Route with Sanctum & Issuing Token

Route::post('/v1/register', function (Request $request) {

    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
                           'email' => 'required|string|email|max:255|unique:users',
                           'password' => 'required|string|min:8',
        ]);
        
              $user = User::create([
                      'name' => $validatedData['name'],
                           'email' => $validatedData['email'],
                           'password' => Hash::make($validatedData['password']),
               ]);

        // issue token
        $token = $user->createToken('auth_token')->plainTextToken;
        
        return response()->json([
                      'access_token' => $token,
                           'token_type' => 'Bearer',
        ]);

});

Creating endpoints with sanctum middleware

Route::middleware('auth:sanctum')->get('/v1/Customer/', [App\Http\Controllers\CustomerController::class, 'index'])->name('Customer.list');
Route::middleware('auth:sanctum')->get('/v1/Customer/create/', [App\Http\Controllers\CustomerController::class, 'create'])->name('Customer.create');
Route::middleware('auth:sanctum')->get('/v1/Customer/{id}', [App\Http\Controllers\CustomerController::class, 'show'])->name('Customer.show');
Route::middleware('auth:sanctum')->get('/v1/Customer/edit/{id}', [App\Http\Controllers\CustomerController::class, 'edit'])->name('Customer.edit');
Route::middleware('auth:sanctum')->post('/v1/Customer/store/{$type?}', [App\Http\Controllers\CustomerController::class, 'store'])->name('Customer.store');
Route::middleware('auth:sanctum')->put('/v1/Customer/{id}', [App\Http\Controllers\CustomerController::class, 'update'])->name('Customer.update');
Route::middleware('auth:sanctum')->delete('/v1/Customer/{id}', [App\Http\Controllers\CustomerController::class, 'destroy'])->name('Customer.destroy');

Leave a comment