article

Saturday, September 10, 2022

Laravel 9 Sanctum Authentication with CRUD REST API - Create Read Update and Delete

Laravel 9 Sanctum Authentication with CRUD REST API - Create Read Update and Delete

Laravel Sanctum is useful for building token-based APIs and tedious authentication systems for single-page applications, mobile applications.

Laravel Sanctum stores user API tokens in a single database table and authenticates incoming HTTP requests

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel>composer create-project --prefer-dist laravel/laravel my-app

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Add Laravel Sanctum Library in Laravel

composer require laravel/sanctum
C:\xampp\htdocs\laravel>composer require laravel/sanctum

publish the sanctum configuration file
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
C:\xampp\htdocs\laravel>php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

app/Http/Kernel.php

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

Database Migration

php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

check user model app/Models/User.php

Add Table in Database

php artisan make:model Task -m
C:\xampp\htdocs\laravel\my-app>php artisan make:model Task -m

update app/Models/Task.php
app/Models/Task.php
//app/Models/Task.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 
        'details'
    ]; 
}
open database/migrations/create_tasks_table.php then update the code
database/migrations/create_tasks_table.php
//database/migrations/create_tasks_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTasksTable extends Migration
{
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('details');            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}
migrate the new table into the database.

C:\xampp\htdocs\laravel\my-app>php artisan migrate

Build API Resources

php artisan make:resource Task
C:\xampp\htdocs\laravel\my-app>php artisan make:resource Task

update code app/Http/Resources/Task.php

//app/Http/Resources/Task.ph
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Task extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'details' => $this->details,
            'created_at' => $this->created_at->format('d/m/Y'),
            'updated_at' => $this->updated_at->format('d/m/Y'),
        ];
        //return parent::toArray($request);
    }
}
Build Auth Controller

create three new controllers

app/Http/Controllers/API/BaseController.php
app/Http/Controllers/API/TaskController.php
app/Http/Controllers/API/AuthController.php

app/Http/Controllers/API/BaseController.php
//app/Http/Controllers/API/BaseController.php
<?php

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

class BaseController extends Controller
{

    public function handleResponse($result, $msg)
    {
    	$res = [
            'success' => true,
            'data'    => $result,
            'message' => $msg,
        ];
        return response()->json($res, 200);
    }

    public function handleError($error, $errorMsg = [], $code = 404)
    {
    	$res = [
            'success' => false,
            'message' => $error,
        ];
        if(!empty($errorMsg)){
            $res['data'] = $errorMsg;
        }
        return response()->json($res, $code);
    }
}
app/Http/Controllers/API/TaskController.php
//app/Http/Controllers/API/TaskController.php
<?php
namespace App\Http\Controllers\API;
   
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Http\Resources\Task as TaskResource;
use App\Models\Task;
use Validator;

class TaskController extends BaseController
{

    public function index()
    {
        $tasks = Task::all();
        return $this->handleResponse(TaskResource::collection($tasks), 'Tasks have been retrieved!');
    }

    
    public function store(Request $request)
    {
        $input = $request->all();
        $validator = Validator::make($input, [
            'name' => 'required',
            'details' => 'required'
        ]);
        if($validator->fails()){
            return $this->handleError($validator->errors());       
        }
        $task = Task::create($input);
        return $this->handleResponse(new TaskResource($task), 'Task created!');
    }

   
    public function show($id)
    {
        $task = Task::find($id);
        if (is_null($task)) {
            return $this->handleError('Task not found!');
        }
        return $this->handleResponse(new TaskResource($task), 'Task retrieved.');
    }
    

    public function update(Request $request, Task $task)
    {
        $input = $request->all();

        $validator = Validator::make($input, [
            'name' => 'required',
            'details' => 'required'
        ]);

        if($validator->fails()){
            return $this->handleError($validator->errors());       
        }

        $task->name = $input['name'];
        $task->details = $input['details'];
        $task->save();
        
        return $this->handleResponse(new TaskResource($task), 'Task successfully updated!');
    }
   
    public function destroy(Task $task)
    {
        $task->delete();
        return $this->handleResponse([], 'Task deleted!');
    }
}
app/Http/Controllers/API/AuthController.php
//app/Http/Controllers/API/AuthController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Validator;

class AuthController extends BaseController
{

    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $auth = Auth::user(); 
            $success['token'] =  $auth->createToken('LaravelSanctumAuth')->plainTextToken; 
            $success['name'] =  $auth->name;
   
            return $this->handleResponse($success, 'User logged-in!');
        } 
        else{ 
            return $this->handleError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'confirm_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->handleError($validator->errors());       
        }
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('LaravelSanctumAuth')->plainTextToken;
        $success['name'] =  $user->name;
   
        return $this->handleResponse($success, 'User successfully registered!');
    }
   
}
Register New Routes

routes/api.php
//routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\API\TaskController;
use App\Http\Controllers\API\AuthController;

//Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
//    return $request->user();
//});

Route::middleware('auth:sanctum')->group( function () {
    Route::resource('tasks', TaskController::class);
});

Route::post('login', [AuthController::class, 'login']);
Route::post('register', [AuthController::class, 'register']);
Test Laravel Auth APIs
C:\xampp\htdocs\laravel\my-app>php artisan serve

Check API Results in Postman
https://www.postman.com/downloads/

POST method : http://127.0.0.1:8000/api/register
POST method : http://127.0.0.1:8000/api/login

After testing auth APIs copy token value and paste to Authorization tab then select Bearer Token
POST method : http://localhost:8000/api/tasks
GET method : http://127.0.0.1:8000/api/tasks

POST method : http://localhost:8000/api/tasks/1
key value
_method PUT
DELTE method : http://127.0.0.1:8000/api/tasks/1

Related Post