In this tutorial you will learn about the Laravel 9 Crud Rest Api with Passport Auth and its application with practical example.
In this Laravel 9 CRUD Api with Passport Auth Tutorial I will show you how to create CRUD REST API with passport authentication In laravel 9. In this tutorial you will learn to create crud and authentication rest api using passport authentication In laravel 9 application. In this article I will share example to create rest api for crud operations and user authentication in laravel 9. We will be creating simple crud operation application with user authentication. We will be using passport authentication package in this example. In this example you will learn how to install passport authentication package in laravel 9. After installing and configure passport authentication in laravel.
- Laravel 9 User Authentication API
- Laravel 9 CRUD REST API
- Laravel 9 Crud Rest Api with Passport Auth
Laravel 9 User Authentication API
In this example we will be creating user authentication api means we will be creating rest api for user registration, login and to get user info. We will be using passport authentication for creating rest api for user authentication.
Laravel 9 CRUD REST API
We will be creating simple product crud operation application with user authentication. In this article, you will learn how to create fully functional CRUD (Create, Read, Update and Delete) REST API in laravel 9.
Laravel 9 Crud Rest Api with Passport Auth
In this step by step tutorial I will guide you through create a fully functional CRUD API with passport authentication in Laravel 9. Please follow the instruction given below:
- Install Laravel 9
- Set Up Database
- Install Passport Package
- Configure Passport Module
- Create Post Model & Run Migration
- Create a New Controller
- Define API Routes
- Test Laravel Passport API
Install Laravel 9
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Configure Database
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=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Install Passport Package
In this step, we need to install Laravel Passport package via the composer dependency manager. Use the following command to install passport package.
1 |
composer require laravel/passport |
After successfully install laravel passport, register providers. Open config/app.php . Put the bellow code in it:
config/app.php
1 2 3 4 5 |
// config/app.php 'providers' =>[ Laravel\Passport\PassportServiceProvider::class, ], |
Now, it is mandatory to install passport using the command below. This command will generate encryption keys required to generate secret access tokens.
1 |
php artisan passport:install |
Passport Configuration
Open User.php model file and add ‘Laravel\Passport\HasApiTokens’ trait in it.
app/Models/User.php
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 |
<?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; use Laravel\Passport\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', ]; } |
go to app/Providers/AuthServiceProvider.php file and register the registerPolicies() method inside the boot() function.
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 |
<?php namespace App\Providers; use Laravel\Passport\Passport; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); } } |
config/auth.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php return [ ..... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], ..... ] |
Create Product Table and Model
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Product -m |
Once above command is executed there will be a migration file created inside database/migrations/ directory, just open create_products_table.php migration file and update the function up() method 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 34 35 36 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('detail'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } } |
Next, go to app/Models/Product.php file and add the $fillable property in the Product model as following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'detail' ]; } |
Run Migration
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Create Passport Auth API Controller
Now, lets create a controller named PassportAuthController using command given below –
1 |
php artisan make:controller Api\PassportAuthController |
Once the above command executed, it will create a controller file PassportAuthController.php in app/Http/Controllers/Api/ directory. Open the PassportAuthController.php file and put the following code in it.
app/Http/Controllers/Api/PassportAuthController.php
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 |
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; class PassportAuthController extends Controller { /** * Registration Req */ public function register(Request $request) { $this->validate($request, [ 'name' => 'required|min:4', 'email' => 'required|email', 'password' => 'required|min:8', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password) ]); $token = $user->createToken('Laravel9PassportAuth')->accessToken; return response()->json(['token' => $token], 200); } /** * Login Req */ public function login(Request $request) { $data = [ 'email' => $request->email, 'password' => $request->password ]; if (auth()->attempt($data)) { $token = auth()->user()->createToken('Laravel9PassportAuth')->accessToken; return response()->json(['token' => $token], 200); } else { return response()->json(['error' => 'Unauthorised'], 401); } } public function userInfo() { $user = auth()->user(); return response()->json(['user' => $user], 200); } } |
Create Product CRUD API Controller
Next we will create product crud api controller named ProductController using command given below –
1 |
php artisan make:controller Api\ProductController |
Once the above command executed, it will create a controller file ProductController.php in app/Http/Controllers/Api/ directory. Open the ProductController.php file and put the following code in it.
app/Http/Controllers/Api/ProductController.php
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use App\Models\Product; use Illuminate\Http\Request; use Validator; class ProductController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $products = Product::all(); return response()->json([ "success" => true, "message" => "Product List", "data" => $products ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $input = $request->all(); $validator = Validator::make($input, [ 'name' => 'required', 'detail' => 'required' ]); if($validator->fails()){ return $this->sendError('Validation Error.', $validator->errors()); } $product = Product::create($input); return response()->json([ "success" => true, "message" => "Product created successfully.", "data" => $product ]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $product = Product::find($id); if (is_null($product)) { return $this->sendError('Product not found.'); } return response()->json([ "success" => true, "message" => "Product retrieved successfully.", "data" => $product ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, Product $product) { $input = $request->all(); $validator = Validator::make($input, [ 'name' => 'required', 'detail' => 'required' ]); if($validator->fails()){ return $this->sendError('Validation Error.', $validator->errors()); } $product->name = $input['name']; $product->detail = $input['detail']; $product->save(); return response()->json([ "success" => true, "message" => "Product updated successfully.", "data" => $product ]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Product $product) { $product->delete(); return response()->json([ "success" => true, "message" => "Product deleted successfully.", "data" => $product ]); } } |
Define API Routes
Now we will define authentication and crud rest API routes. Go to the routes directory and open api.php. Then put the following routes into api.php file:
routes/api.php
1 2 3 4 5 6 7 8 9 10 11 12 |
use App\Http\Controllers\API\PassportAuthController; use App\Http\Controllers\API\ProductController; Route::post('register', [PassportAuthController::class, 'register']); Route::post('login', [PassportAuthController::class, 'login']); Route::middleware('auth:api')->group(function () { Route::get('get-user', [PassportAuthController::class, 'userInfo']); Route::resource('products', [ProductController::class]); }); |
Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Laravel 9 User Registration API:
1 |
http://localhost:8000/api/register |
Laravel 9 User Login API:
1 |
http://localhost:8000/api/login |
Laravel 9 Get User Info. API:
Product List API
1 |
http://localhost:8000/api/products |
Product Create API
Method:- POST
1 |
http://localhost:8000/api/products |
Product Fetch API
Method:- GET
1 |
http://localhost:8000/api/products/{id} |
Product Update API
Method:- PUT
1 |
http://localhost:8000/api/products/{id} |
Product Delete API
Method:- DELETE
1 |
http://localhost:8000/api/products/{id} |