In this tutorial you will learn about the Build Secure PHP REST API in Laravel 8 with Sanctum Auth and its application with practical example.
In this Build Secure PHP REST API in Laravel 8 with Sanctum Auth Tutorial I will show you how to create REST API with Sanctum authentication In laravel. In this tutorial you will learn to create rest api with Sanctum authentication In laravel 8 application. In this article I will share example to create simple crud rest api with sanctum authentication in laravel. I will also show you how to install sanctum auth package in laravel. After installing and configure sanctum authentication in laravel we will create simple crud operation rest api.
- Build Secure PHP REST API in Laravel 8 with Sanctum Auth
- Create Laravel Project
- Add Database Details in ENV
- Install Laravel Sanctum Pacakage
- Setting Up Sanctum
- Update Model and Run Migration
- Build API Resources
- Setting Up Controllers
- Create REST API Routes
- Test Sanctum REST API in Postman
- Test Register REST API
- Test Login API
- Create Post with Sanctum API
- Get Single Post
- Fetch All Posts
- Update Post
- Delete Record
Build Secure PHP REST API in Laravel 8 with Sanctum Auth
In this step by step tutorial I will guide you through create a fully functional restful API with sanctum authentication in Laravel 8. We will be creating fully functional REST API along with sanctum Authentication. Please follow the instruction given below:
- Step 1: Create Laravel Project
- Step 2: Add Database Details
- Step 3: Install Laravel Sanctum Pacakage
- Step 4: Setting Up Sanctum
- Step 5: Update Model and Run Migration
- Step 6: Build API Resources
- Step 7: Set Up Controllers
- Step 8: Create REST API Routes
- Step 09: Test REST API in Postman
Create Laravel Project
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel laravel-sanctum-auth |
Add Database Details in ENV
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db_name DB_USERNAME=root DB_PASSWORD= |
Install Laravel Sanctum Pacakage
In this step, we will install Sanctum Package via the composer dependency manager. Use the following command to install Sanctum Package.
1 |
composer require laravel/sanctum |
Setting Up Sanctum
Now, we need to publish the Sanctum configuration and migration files using the Artisan command.
1 |
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" |
Thereafter, register the sanctum middleware into the api array inside the app/Http/Kernel.php file
1 2 3 4 5 6 7 8 9 10 11 |
protected $middlewareGroups = [ ... ... 'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ... ... ]; |
Now, run following command to migrate database schema along with sanctum tables in our database.
1 |
php artisan migrate |
Lets Import the sanctum HasApiTokens service within the app/Models/User.php. Open App/User.php model file and add ‘Laravel\Sanctum\HasApiTokens’ trait in it.
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 |
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; // sanctum use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; } |
Update Model and Run Migration
Now, in this step we will create migration file. Please run the following command:
1 |
php artisan make:migration create_blogs_table |
Open and add code into the database/migrations/create_blogs_table.php file. Add few properties into the migration file as following.
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 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBlogsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('blogs', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('blogs'); } } |
Next, create an app/Models/Blog.php file and register product migration properties inside the $fillable array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Blog extends Model { use HasFactory; protected $fillable = [ 'title', 'description' ]; } |
Now, run following command to migrate database schema.
1 |
php artisan migrate |
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 |
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller as Controller; class BaseController extends Controller { /** * success response method. * * @return \Illuminate\Http\Response */ public function sendResponse($result, $message) { $response = [ 'success' => true, 'data' => $result, 'message' => $message, ]; return response()->json($response, 200); } /** * return error response. * * @return \Illuminate\Http\Response */ public function sendError($error, $errorMessages = [], $code = 404) { $response = [ 'success' => false, 'message' => $error, ]; if(!empty($errorMessages)){ $response['data'] = $errorMessages; } return response()->json($response, $code); } } |
Open and place all the suggested code into the app/Http/Controllers/API/AuthController.php file.
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 |
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\API\BaseController as BaseController; use Illuminate\Support\Facades\Auth; use Validator; use App\Models\User; class AuthController extends BaseController { public function signin(Request $request) { if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ $authUser = Auth::user(); $success['token'] = $authUser->createToken('MyAuthApp')->plainTextToken; $success['name'] = $authUser->name; return $this->sendResponse($success, 'User signed in'); } else{ return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']); } } public function signup(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'confirm_password' => 'required|same:password', ]); if($validator->fails()){ return $this->sendError('Error validation', $validator->errors()); } $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $success['token'] = $user->createToken('MyAuthApp')->plainTextToken; $success['name'] = $user->name; return $this->sendResponse($success, 'User created successfully.'); } } |
Now go to the app/Http/Controllers/API/BlogController.php file and insert the CRUD operations code into it:
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 69 70 71 |
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\API\BaseController as BaseController; use Validator; use App\Models\Blog; use App\Http\Resources\Blog as BlogResource; class BlogController extends BaseController { public function index() { $blogs = Blog::all(); return $this->sendResponse(BlogResource::collection($blogs), 'Posts fetched.'); } public function store(Request $request) { $input = $request->all(); $validator = Validator::make($input, [ 'title' => 'required', 'description' => 'required' ]); if($validator->fails()){ return $this->sendError($validator->errors()); } $blog = Blog::create($input); return $this->sendResponse(new BlogResource($blog), 'Post created.'); } public function show($id) { $blog = Blog::find($id); if (is_null($blog)) { return $this->sendError('Post does not exist.'); } return $this->sendResponse(new BlogResource($blog), 'Post fetched.'); } public function update(Request $request, Blog $blog) { $input = $request->all(); $validator = Validator::make($input, [ 'title' => 'required', 'description' => 'required' ]); if($validator->fails()){ return $this->sendError($validator->errors()); } $blog->title = $input['title']; $blog->description = $input['description']; $blog->save(); return $this->sendResponse(new BlogResource($blog), 'Post updated.'); } public function destroy(Blog $blog) { $blog->delete(); return $this->sendResponse([], 'Post deleted.'); } } |
Create REST API Routes
After this, we need to define routes in “routes/api.php” file. Lets open “routes/api.php” file and add the following routes in it.
routes/api.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\API\AuthController; use App\Http\Controllers\API\BlogController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- */ Route::post('login', [AuthController::class, 'signin']); Route::post('register', [AuthController::class, 'signup']); Route::middleware('auth:sanctum')->group( function () { Route::resource('blogs', BlogController::class); }); |
Test Sanctum REST API in Postman
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Test Register REST API
1 |
http://localhost:8000/api/register |
Test Login API
1 |
http://localhost:8000/api/login |
Create Post with Sanctum API
1 |
http://localhost:8000/api/blogs |
Get Single Post
1 |
http://localhost:8000/api/blogs/{id} |
Fetch All Posts
1 |
http://localhost:8000/api/blogs |
Update Post
1 |
http://localhost:8000/api/blogs/{id} |
Delete Record
1 |
http://localhost:8000/api/blogs/{id} |