Updated 17 May 2023
Hello guys, So in this article, I will show you how to authenticate to API in Laravel using Sanctum. This is very useful when you are building an API for a SPA.
This is a very simple project so follow these steps written below.
1 |
composer create-project laravel/laravel --prefer-dist laravel-sanctum |
1 |
composer require laravel/sanctum |
1 |
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" |
1 |
php artisan migrate |
So, User model should look like the image below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; } |
1 |
php artisan make:controller AuthController |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<?php namespace App\Http\Controllers; use App\Models\User; use App\Traits\ApiResponser; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AuthController extends Controller { use ApiResponser; public function register(Request $request) { $request->validate([ 'name' => 'required|string|max:50', 'email' => 'required|string|email|unique:users,email', 'password' => 'required|string|min:6', 'confirm_password' => 'required_with:password|string|min:6|same:password' ]); $user = User::create([ 'name' => $request->name, 'password' => bcrypt($request->password), 'email' => $request->email ]); return $this->success([ 'token' => $user->createToken('API Token')->plainTextToken ], 'User registration successful!!'); } public function login(Request $request) { $attr = $request->validate([ 'email' => 'required|string|email|', 'password' => 'required|string|min:6' ]); if (! Auth::attempt($attr)) { return $this->error('Credentials did\'t not matched'); } return $this->success([ 'token' => auth()->user()->createToken('API Token')->plainTextToken ], 'Login successfulY'); } public function users() { $users = User::select('name', 'email')->get(); return $this->success([ 'users' => $users ], 'User list featched successfully!!'); } public function logout() { auth()->user()->tokens()->delete(); return response()->json([ 'message' => 'Logout successfully!!' ]); } } |
So, Let’s make a trait inside App/Traits/ApiResponser.php and trait look like shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Traits; trait ApiResponser { protected function success($data, string $message = null) { return response()->json([ 'status' => 'Success', 'message' => $message, 'data' => $data ]); } protected function error(string $message = null, $data = null) { return response()->json([ 'status' => 'Error', 'message' => $message, 'data' => $data ]); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AuthController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "api" middleware group. Make something great! | */ Route::controller(AuthController::class)->group(function () { Route::post('/register', 'register'); Route::post('/login', 'login')->name('login'); }); Route::middleware(['auth:sanctum'])->group(function () { Route::controller(AuthController::class)->group(function () { Route::get('/users', 'users'); Route::get('/logout', 'logout'); }); }); |
Here we are using postman for API testing please refer the below images for better understanding.
Thank you for reading this tutorial. We hope you found it helpful. If you have any questions or encounter any issues, please feel free to leave a comment below.
Additionally, if you’re looking to hire Laravel developers, you can visit the Hire Laravel Developer page. This platform provides a pool of experienced Laravel developers who can help you with your project requirements and ensure the successful implementation of your ideas.
Furthermore, if you’re interested in enhancing the functionality of Bagisto, you can check out the Extensions page on the official Bagisto website. This page showcases a wide range of extensions that can be integrated into your Bagisto e-commerce platform to add new features, improve user experience, and optimize your online store’s performance.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.