Laravel Sanctum – login and Registration

version : Laravel 10
Post Time : 02-05-2024

Laravel Sanctum - Login and Registration

install Laravel

          - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_sanctum_demo

app/Http /kernel.php file
Uncomment   this line :-

\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

                                      
                                        

<?php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel

{
     …
     …
      'api' => [

          \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
          \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
          \Illuminate\Routing\Middleware\SubstituteBindings::class,
       ],
   ];
    …
    …

Create Database in Mysql and set that Database in .env file

Then run following Command 

                                      
                                        

php artisan migrate
php artisan make:controller API\AuthController

app/Http/Controllers/API/AuthController.php

                                      
                                        

<?php

namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Auth;
use Validator;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
  /*----------------------Register------------------------*/
   public function register(request $request)
   {
       $validator = Validator::make($request->all(),[
          'name'=> 'required',
          'email' => 'required|email|unique:users,email',
          'password' => 'required',
          'c_password' => 'required|same:password',
      ]);
      if($validator->fails()){
           $response = [
              'success' => false,
              'message' => $validator->errors()
           ];
           return response()->json($response, 400);
      }
      $input =$request->all();
      $input['password'] = Hash::make($input['password']);
      $user = User::create($input);
      $success['token'] = $user->createToken('MyApp')->plainTextToken;
      $success['name'] = $user->name;
      $response =[
          'success'=> true,
          'data' => $success,
          'message' => 'User Register Sucessfully',
      ];
      return response()->json($response,200);
   }

  /*----------------------Login------------------------*/
   public function login(request $request)
   {
       $validator = Validator::make($request->all(),[
           'email' => 'required |email',
           'password' => 'required',
       ]);
      if($validator->fails()){
           $response = [
              'success' => false,
              'message' => $validator->errors()
           ];
           return response()->json($response, 400);
       }
      if(Auth::attempt(['email' =>$request->email,'password'=>$request->password]))
       {
          $user = Auth::user();
          $success['token'] = $user->createToken('MyApp')->plainTextToken;
          $success['name'] = $user->name;
           $response =[
              'success'=> true,
               'data' => $success,
              'message' => 'User Register Sucessfully',
           ];
           return response()->json($response,200);
       }else{
           $response = [
              'success' => false,
              'message' => 'Unauthorized',
           ];
           return response()->json($response);
       }   
   }
}

routes/api.php

                                      
                                        

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\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::middleware('auth:sanctum')->get('/user', function (Request $request) {
   return $request->user();
});

Route::post('login', [AuthController::class, 'login']);
Route::post('register', [AuthController::class, 'register']);

Register Api :-
Method :- POST
url :- http://localhost:8000/api/register
Parameter :-
name , email , password, c_password

Login Api :-
Method :- POST
Url :- http://localhost:8000/api/login
Parameter :-
Email , Password