
Laravel 8 tutorial – API authentication with Sanctum
Create Laravel Project
composer create-project laravel/laravel --prefer-dist lekhapora
Then go to your project folder and open it with any code editor
setup database in .env file
DB_DATABASE=lekhapora
DB_USERNAME=root
DB_PASSWORD= Password
Install Laravel Sanctum.
composer require laravel/sanctum
Publish the Sanctum configuration and migration files .
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Run your database migrations.
php artisan migrate
Add the Sanctum’s middleware.
../app/Http/Kernel.php
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
...
protected $middlewareGroups = [
...
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
...
],
To use tokens for users.
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Let’s create the seeder for the User model
php artisan make:seeder UsersTableSeeder
Now let’s insert as a record
You can see our user table is blank. U can manually import user information but we cant password hashing that’s why we used seeder
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
...
...
DB::table('users')->insert([
'name' => 'Pallab Mallick',
'email' => 'pallab@gmail.com',
'password' => Hash::make('123')
]);
To seed users table with user
php artisan db:seed --class=UsersTableSeeder
pallab@pallab-NE572:~/p/API-Sanctum/lekhapora$ php artisan db:seed --class=UsersTableSeeder
Database seeding completed successfully.
pallab@pallab-NE572:~/p/API-Sanctum/lekhapora$
create a controller nad /login route in the routes/api.php file:
Create a Controller
php artisan make:controller UserController
Paste the below code in your UserController.php file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
//
function index(Request $request)
{
$user= User::where('email', $request->email)->first();
// print_r($data);
if (!$user || !Hash::check($request->password, $user->password)) {
return response([
'message' => ['These credentials do not match our records.']
], 404);
}
$token = $user->createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
}
Go to routes→api.php import user model and login routes
use App\Http\Controllers\UserController;
Route::post("login",[UserController::class,'index']);
Then Run your project
php artisan serve
Test with postman, Result will be below
Now we need if the user logged in then the user can add product
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\DeviceController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => 'auth:sanctum'], function(){
//All secure URL's
Route ::post('/addproduct',[DeviceController::class,'addProduct']);
});
Route::post("login",[UserController::class,'index']);
What we did in this code, we had already created DeviceController, model, and import it to api.php file. To secure our API we put it under Route middleware