Laravel API With Sanctum

 Laravel API With Sanctum


  • Install a Laravel project
        composer create-project laravel/laravel [my-project-name]
  • Install the package
        Composer require laravel/sanctum
  • Do the migration
        php artisan vendor:publish --provider=”Laravel\Sanctum\SanctumServiceProvider” 
php artisan migrate

  • Replace the kernel.php -> middlewareGroups -> api


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

  • Add this to User model
        use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{ use HasApiTokens, HasFactory, Notifiable;}


  • Add this to api.php routes
        Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/employees/search/{name}', [EmployeeController::class, 'search']);
});

  • Try it with postman (make sure you are defining the header)

  • Separate routes in a better manner
<?php
use App\Http\Controllers\EmployeeController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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:api')->get('/user', function (Request $request) {
return $request->user();
});

//public routes
Route::get('/employees/search/{name}', [EmployeeController::class, 'search']);
Route::get('/employees', [EmployeeController::class, 'index']);
// Route::resource('employees', EmployeeController::class);

//protected routes
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('/storeEmployees', [EmployeeController::class, 'store']);
Route::put('/updateEmployees/{id}', [EmployeeController::class, 'update']);
Route::delete('/deleteEmployees/{id}', [EmployeeController::class, 'destroy']);
});

Authentication Part

  • Create a controller
        php artisan make:controller AuthController

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $fields = $request->validate([
            'name' => 'required|string',
            'email' => 'required|unique:users,email',
            'password' => 'required|confirmed'
        ]);

        $user = User::create([
            'name' => $fields['name'],
            'email' => $fields['email'],
            'password' => bcrypt($fields['password'])
        ]);

        $token = $user->createToken('myapptoken')->plainTextToken;

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response, 201);
    }
}

  • Create a route for this
Route::post('/register', [AuthController::class, 'register']);

  • Check with postman

  • Copy the token and go to Authorization tab which of the request you are willing to do and select bearer token from the dropdown
  • Then copy the token and run


Logging Out

  • Create a logout function in AuthController
public function logout(Request $request)
{
  auth()->user()->tokens()->delete();
  return [
    'message' => 'Logged Out'
  ];
}
  • Create the protected route
//protected routes
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('/storeEmployees', [EmployeeController::class, 'store']);
Route::put('/updateEmployees/{id}', [EmployeeController::class, 'update']);
Route::delete('/deleteEmployees/{id}', [EmployeeController::class, 'destroy']);
Route::post('/logout', [AuthController::class, 'logout']);
});
  • Check with postman

Logging In

  • Create a login function in AuthController
function login(Request $request)
{
    $fields = $request->validate([
    'email' => 'required,
    'password' => 'required
  ]);
  //Check email
  $user = User::where('email', $fields['email'])->first();
  //Check password
  if(!$user || !Hash::check($fields['password'], $user->password))
  {
    return response([
    'message' => 'Bad Credentials'
    ], 401);
  }
  $token = $user->createToken('myapptoken')->plainTextToken;
  $response = [
    'user' => $user,
    'token' => $token
  ];
  return response($response, 201);
}
  • Create the public route
//public routes
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::get('/employees/search/{name}', [EmployeeController::class, 'search']);
Route::get('/employees', [EmployeeController::class, 'index']);
  • Check with postman by providing wrong credentials
  • Now check with correct credentials

  • Thank You!!!

Comments

  1. This is a very good blog for me because I was stuck with developing Sanctum token and thank you very much.

    ReplyDelete

Post a Comment

Popular posts from this blog

Google authentication with Laravel

Load balance with NGINX