Laravel CRUD API with Token Based Authentication with Sanctum

As we all know, with the implementations and integration of Application Programming Interfaces, the work load on developers have reduced quite a lot. Here in this tutorial, we will be building an API to minimize the platform agnostic approach of conventional web development and continue with the flow of current era.

Lets start with the basics, Laravel.

Prerequisites of Laravel, we all know is PHP Version 7.3+ and Composer, a package manager for PHP. In other languages like JavaScript you would use something like Node Package Manager or NPM or Yarn.

To create a new Laravel project, we simply have to install it globally by a simple command composer global require laravel/laravel. Once the process has finished, simply exit your terminal or command prompt and run another command laravel new <your_project_name>. If this does not work, don’t worry, just use the command composer create-project laravel/installer <your_project_name>. Once done, we can now start with our development activities.

Create the database and configure your project with database

Create a database with PHP MyAdmin or MySQL Workbench. In your .env file, add your database DB_HOST, DB_DATABASE, DB_USER and DB_PASSWORD as per your settings. Once done, we are ready to start our work with configuring and setting up our Sanctum authentication.

Sanctum – An Overview

Before we dive deep in code, we need to know what Sanctum is and how it works. Basically Sanctum provides a lightweight authentication for Single Page Applications or SPA, Mobile Applications and Simple Token Based Web APIs. It allows users to generate tokens for their accounts, these may be used for Role Based Access Controls or such other implementations.

Installation

To install Sanctum, you just need to perform a few steps mentioned in laravel documentation. Yes, Laravel Docs, it provides a very descriptive installation which we will see. Hats off to writers for writing such an artistic documentation for a third party package.

Simply run a command,

composer require laravel/sanctum

in your terminal or command prompt in your project’s root directory.

Voila, it is in. Now we just have publish our Sanctum configuration. Just run a command

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

After that, you should be able to see an output like:

vendor-publish
publishing

Now run your migration by running the command php artisan migrate. You will see the migration output like:

migration

Navigate to app/Http/Kernel.php. Find the middlewareGroup’s api driver and update your code block

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

There, you are ready to use sanctum. Lets move to the fun part.

Performing CRUD operations

Create a resource group with a simple command,

php artisan make:model Product -a

This command will make a Controller, Model, Migration, Seeder and Factory classes in their respective directories. Modify your product migration:

create_products_migration

Update your Product Model,

In your User model, you will need to add use Laravel\Sanctum\HasApiTokens;in your namespaces as well as update your drivers like use HasFactory, Notifiable, HasApiTokens;

Note: This part is necessary to perform, else your API drivers will not be able to issue tokens to the user.

Lets move to our controller. Run the php artisan make:controller AuthController command to make a controller for authentication.

AuthController.php

Modify your product controller

ProductController.php

In your routes/api.php file, register your routes for the api

api.php

Voila, your API is ready to run, use any API testing tool like Insomnia or Postman.

Start your application by php artisan serve command and make a request to any of the registered routes, if you try to send a request to a protected route, you will get response of else you will be able to perform the operation

{
      "message": "Unauthenticated"
}

Use your API in a mobile app, or use on a desktop application, it’s seamless!

Leave a Reply

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