Introduction
Laravel Sanctum authentication tutorial; In this tutorial, we will share how to create or build a secure PHP RESTful API in Laravel application with the help of the Laravel sanctum package. Likewise, we will explain to you step by step how to test the Laravel Sanctum authentication REST API using the Postman testing tool.
Laravel Sanctum provides a lightweight authentication system for SPAs (single-page applications), mobile apps, and simple token-based APIs. Sanctum allows users of your application to create multiple API tokens. These tokens can be granted capabilities / scopes that specify the actions they are allowed to perform.
So, let’s start creating the sanctum rest api in the laravel application without getting into theories.
Laravel 9 REST API with Sanctum Auth
Here are the instructions going toward building an uncomplicated, secure restful api in the laravel app.
- Step 1: Create Laravel Project
- Step 2: Configure Database
- Step 3: Install Laravel Sanctum Pacakage
- Step 4: Build API Resources
- Step 5: Set Up Controllers
- Step 6: Create REST API Routes
- Step 7: Test REST API in Postman
Create Laravel Project
Before creating a Laravel project, ensure that your local machine has PHP and Composer installed. On macOS, PHP and Composer can be installed via Homebrew. In addition, installing Node and NPM is recommended.
You can check out the laravel docs on other methods to create a laravel project.
Configure database in .env
You have to add the database details into the .env configuration file to communicate between the laravel and mysql database.
Note – Append UNIX_SOCKET and DB_SOCKET variables if developing using MAMP on MacOs:
Install Laravel Sanctum Pacakage
Install Laravel Sanctum via the Composer package manager:
Next, proceed to publish the Sanctum configuration and migration files using the vendor:publish
Artisan command. The sanctum
configuration file will be placed in your application’s config
directory:
Next, proceed to include Sanctum’s middleware to your api
middleware group within your application’s app/Http/Kernel.php
file:
Finally, run your database migrations. Sanctum will create one database table in which to store API tokens:
Create Product model and migration
Use php artisan command to create a new Product model and product migration table, the -m flag generates the migration for the model.
You need to add a few properties into the migration file created, open and add code into the database/migrations/{timestamp}create_products_table.php file.
Note – The migrations are created prepended with a specific timestamp i.e 2022_06_17_113117_create_products_table.php
in our case
Next, add $fillable
array properties for for the Product model in app/Models/Product.php file. This simply is defining which model attributes you want to make mass assignable. In our case its name and description.
Proceed to run the database migration:
Create API Resources
Laravel API Resources creates a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application’s users.
Execute command to generate Product eloquent api resources.
Place the code below into the app/Http/Resources/Product.php
file:
Creating Controllers
Next, we need to create three controllers to handle the auth process; first, create an API directory into the Controllers folder; after that, create three files simultaneously within the folder name them AuthController, BaseController and ProductController.
These files will individually handle login, signup and blogs crud operations.
Subsequently, add the code in the app/Http/Controllers/API/BaseController.php file:
Open and place all the suggested code into the app/Http/Controllers/API/AuthController.php file, it will amplify the user registration and signin process:
Head over to the app/Http/Controllers/API/BlogController.php file and insert the CRUD operations code into it:
Create REST API Routes
You need to use controllers to build sanctum auth api routes; we have defined the login, register post methods and resources to create auth api collectively.
Open and insert code into routes/api.php file:
Test Sanctum REST API in Postman
We have created the REST API using sanctum auth; further you need to start the laravel development server with the help of the php artisan command:
With the help of Postman, we will test the Laravel Sanctum authentication APIs:
Test Register REST API
Open the Postman app, select the Post method from the dropdown. Enter the route or URL in the address bar, select the Body section, enter name, email, password and confirm the password and click on send to create a user using laravel sanctum auth api.
Test Login API
Add the following URL in the postman address bar, switch the method to GET, enter email and password and click on send to login a user.
Set Authorization Token
Get into the Postman app’s Authorization tab, select ‘Bearer Token’ from the Type dropdown, then add the auth token that you got when logged into the app.
Create Post with Sanctum API
Add the following URL in the postman address bar, switch the method to POST, enter title and description then click to create a post and store into the database.
Get Single Post
You can now see how to fetch single post using the post id and rest api, use the given below url:
Fetch All Posts
You can fetch all the posts at once, hence use the following REST API with GET method to get all the records.
Update Post
Update a post using sanctum auth restful api, add the following route with Put method to update a single record into the database.
Delete Record
To delete a record set the method to delete and use the following url:
Conclusion
The Laravel Sanctum authentication tutorial is over; throughout this detailed guide, you explored bit by bit how to create and test authentication REST API in laravel with the help of Sanctum auth package and Postman api testing tool.
When it comes to security, flexibility, and ease of use, there is nothing better than Sanctum auth api.
You may also take the help of Laravel sanctum auth API to add authentication in your next laravel project. We assume you liked this comprehensive example, so don’t forget to share it with others.