Laravel sactume

composer create-project --prefer-dist laravel/laravel laravel_sanctum

Now would be a good time to start the Laravel application to make sure everything is working as expected:

cd laravel_sanctum
php artisan serve

Installation and Setup

With the Laravel application in place, let’s add Laravel Sanctum to it. First, we need to install Laravel Sanctum into our application using Composer:

composer require laravel/sanctum

Next, we’ll publish Laravel Sanctum configuration and migration files using the following command:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Then update the .env file as below:

DB_DATABASE=db_name

Now, run the database migrations:

php artisan migrate

In addition to the tables that come with a default Laravel, this will create a personal_access_tokens table in the database where all tokens will be stored.

// app/Models/User.php

use Laravel\Sanctum\HasApiTokens;

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

Building the API

Let’s start with registering for an account. In your terminal create the controller responsible for authentication by running the following Artisan command:

php artisan make:controller AuthController

Now open the routes/api.php file to create the route responsible for registering a user:

// routes/api.php
use App\Http\Controllers\AuthController;

Route::post('/register', [AuthController::class, 'register']);

Open up the AuthController and add the code snippet below in it to create the method to register a user:

// app/Http/Controllers/AuthController.php
use Illuminate\Support\Facades\Hash;

public function register(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']),
       ]);

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

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

Next, let’s add the implementation for returning users to login. Add the code below inside routes/api.php:

// routes/api.php

Route::post('/login', [AuthController::class, 'login']);

Then add the login() method inside of the AuthController:

// app/Http/Controllers/AuthController.php

use App\Models\User;
use Illuminate\Support\Facades\Auth;

public function login(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',
]);
} Let’s add the last functionality, which is for fetching the currently authenticated user. Add the code below inside routes/api.php:
// routes/api.php

Route::post('/me', [AuthController::class, 'me']);

Next, add the following code to the AuthController:

// app/Http/Controllers/AuthController.php

public function me(Request $request)
{
return $request->user();
}

So let’s update the route as below:

// routes/api.php

Route::post('/me', [AuthController::class, 'me'])->middleware('auth:sanctum');

Before we test the API, let’s uncomment the line below inside app/Providers/RouteServiceProvider.php:

// app/Providers/RouteServiceProvider.php

protected $namespace = 'App\\Http\\Controllers';

Testing the API

php artisan serve
The application should be running on http://127.0.0.1:8000 and we can access the API on http://127.0.0.1:8000/api.

Login the user

To login, make a POST request to http://127.0.0.1:8001/api/login with your email and password (in plain text format.

Otherwise, we should get user details as in the image below:

Leave a Reply

Your email address will not be published. Required fields are marked *