Spread the love

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. When you think of simple middle level laravel API authentication sanctum is the best choice.

Lets get started assuming that you’ve already setup your laravel project and configured database connections. If you’re not read how to setup laravel project. and database connectivity.

Step 1: Sanctum Installation

Use composer package manager

composer require laravel/sanctum

Next, publish Laravel Sanctum configuration and migration files

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

Finally, you should run your database migrations. Sanctum will create one database table in which to store API tokens:

php artisan migrate

Make sure your User model use the Laravel\Sanctum\HasApiTokens trait: if not add it.

use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
    use HasApiTokens, HasFactory, Notifiable;

Step 2: Create Controller

Use artisan make command to create a controller

php artisan make:controller Api\AuthController

By executing the command, a file “AuthController.php” will be generated inside “app/Http/Controllers/Api” folder.

Step 3: Registration

Open the controller that we created now “AuthController.php” and add the following method inside

    public function register(Request $request)
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users|max:255',
            'name' => 'required|string|max:255',
            'password' => 'required|min:6',

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'error' => $errors
            ], 400);

        if ($validator->passes()) {
            $user = User::create([
                'email' => $request->email,
                'name' => $request->name,
                'password' => Hash::make($request->password)
            // You should always get the plain text of the token immediately after the token has been created:
            $token = $user->createToken('token_name')->plainTextToken;
            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',

Don’t forget to get the plain text of the newly created token immediately. Unless you’ll never find it again. it will be hashed using SHA-256 hashing before it stored in your database. This hashing algorithm is a one way hashing algorithm.

Step 4: Login

Inside the  “AuthController.php” add the following login method

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

        $user = User::where('email', $request['email'])->firstOrFail();

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

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

Step 5: User Profile

To get logged in user details use the following method. Laravel API Authentication

    public function profile(Request $request)
        return $request->user();

Step 6: Routing

After setting up the controller we specify a route for each methods. Open “routes/api.php" and add the following code.

Route::post('/register', 'AuthController@register');
Route::post('/login', 'AuthController@login');
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/profile', 'AuthController@me');

As you see above we’ve defined a route for each methods. The route of profile is different from others that is because it needs to be accessible to only authenticated users. 

Another thing is setting up “/api” route for our Api. Open this file app/Providers/RouteServiceProvider.php and add the following code at global level inside the RouteServiceProvider class.

class RouteServiceProvider extends ServiceProvider
    protected $namespaceApi = 'App\\Http\\Controllers\\Api';

Then, inside the boot function add this code snippet. Just to remind copy the Route:: part of the code. not all of it.

    public function boot()
        $this->routes(function () {


Voila! We’re done. Now lets run and test it.

I use Thunder Client Rest Client for Testing APIs. It is a very nice and easy and light weight Vs Code extension. Hey wait, note that this is not a commercial. it is just a best.


Sanctum Registeration


Sanctum Login


Sanctum logged in profile

1 Comment

Beshir · January 5, 2023 at 5:33 am

My brother A/Hakim go on, on your work. May allah help you

Leave a Reply

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