Home Laravel 9 Laravel 9 Sanctum Authentication REST API

Laravel 9 Sanctum Authentication REST API

3 min read

in this will teach about the Sanctum Authentication REST API with token step by step.
we have created the user register api and login api using Sanctum.

Install laravel

composer create-project laravel/laravel lms-app

after installed  the laravel .Open up the project into vs code editor.

Create the Database in Mysql. which name dblms

After that open the .env file and changes database name as dblms.

Install Laravel Sanctum

composer require laravel/sanctum

Publish Sanctum

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

After that create and tables and token running the migration command

php artisan migrate

After that your tables has been created.and model also created.

Create the Controller

 php artisan make:controller UserController

Inside the UserController paste this below code

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Auth;

class UserController extends Controller

    public function register(Request $request)
          $user = new User();
          $user->name = $request->name;
          $user->email = $request->email;
          $user->password = bcrypt($request->password);

          $token = $user->createToken('API TOKEN');

          return response()->json([
            'message' => "User registered",
            'token' => $token->plainTextToken

    public function login(Request $request)
          return response()->json([
            'message' => "Invalid Username or Password",
      $user = User::where('email', $request->email)->first();
      $token = $user->createToken('API TOKEN');
        return response()->json([
          'message' => "User Logged in",
          'token' => $token->plainTextToken


Open in file api.php


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();


i have attached the video link below. which will do this tutorials step by step.


    Load More Related Articles
    Load More By admin
    Load More In Laravel 9

    Leave a Reply

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

    Check Also

    Build a Full-Stack Node.js MongoDB CRUD App with JWT Authentication

    In this tutorial, we will teach the process of building a full-stack application using Nod…