Laravel 7 REST API With Passport Authentication Tutorial – onlinecode
In this post we will give you information about Laravel 7 REST API With Passport Authentication Tutorial – onlinecode. Hear we will give you detail about Laravel 7 REST API With Passport Authentication Tutorial – onlinecodeAnd how to use it also give you demo for it if it is necessary.
In this tutorial, we are going on how to create rest API using passport authentication in laravel 7. so here we are using the laravel/passport package for rest API.
The Laravel Passport package is provided by laravel framework. so we can easily create and manage the API in laravel. let’s follow the below steps to how to create rest API with authentication in laravel.
Overview
Step 1: Install LaravelStep 2: Install PackageStep 3: Add Service ProviderStep 4: Setting Database ConfigurationStep 5: Run Migration Command and Passport InstallStep 6: Passport ConfigurationStep 7: Create RouteStep 8: Create a ControllerStep 9: Run The Application
Step 1: Install LaravelWe are going to install laravel 6, so first open the command prompt or terminal and go to go to xampp htdocs folder directory using the command prompt. after then run the below command.
composer create-project --prefer-dist laravel/laravel larave7_passport_api
Step 2: Install PackageNow, we are going to install the “laravel/passport” package using the below command.
composer require laravel/passport
Step 3: Add Service ProviderWe will add below providers and aliases in the “config/app.php” file.
'providers' => [ .... LaravelPassportPassportServiceProvider::class, ],
Step 4: Setting Database Configuration
After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Enter_Your_Database_Name(laravel7_passport_api) DB_USERNAME=Enter_Your_Database_Username(root) DB_PASSWORD=Enter_Your_Database_Password(root)
Step 5: Run Migration Command and Passport Install
Now, create the migrate table using the below command and we will create a token key for security using the passport install command.
php artisan migrate
php artisan passport:install
Step 6: Passport Configurationhere, in this step, we have to the configuration in User.php, AuthServiceProvider.php and auth.php. so you can follow the below code.app/User.php
<?php namespace App; use IlluminateContractsAuthMustVerifyEmail; use IlluminateFoundationAuthUser as Authenticatable; use IlluminateNotificationsNotifiable; use LaravelPassportHasApiTokens; class User extends Authenticatable { use Notifiable,HasApiTokens; /** * 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', ]; } ?>
app/Providers/AuthServiceProvider.php
<?php namespace AppProviders; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; use IlluminateSupportFacadesGate; use LaravelPassportPassport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ // 'AppModel' => 'AppPoliciesModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); Passport::tokensExpireIn(now()->addDays(15)); Passport::refreshTokensExpireIn(now()->addDays(30)); } } ?>
config/auth.php
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
Step 7: Create Route
Add the following route code in the “routes/api.php” file.
<?php use IlluminateHttpRequest; use IlluminateSupportFacadesRoute; /* |-------------------------------------------------------------------------- | 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::post('login', 'APIAuthController@login'); Route::post('register', 'APIAuthController@register'); Route::middleware('auth:api')->group(function(){ Route::post('user_detail', 'APIAuthController@user_detail'); }); ?>
Step 8: Create a ControllerNow, we need to create an API directory and controller file, so first we will create an API directory and AuthController.php file. after then created a file then we will create the rest API method. so you can follow the below code.app/Http/Controllers/API/AuthController.php
<?php namespace AppHttpControllersAPI; use AppUser; use Validator; use IlluminateHttpRequest; use AppHttpControllersController; use IlluminateSupportFacadesHash; use IlluminateSupportFacadesAuth; use SymfonyComponentHttpFoundationResponse; class AuthController extends Controller { public function login(Request $request){ $credentials = [ 'email' => $request->email, 'password' => $request->password ]; if( auth()->attempt($credentials) ){ $user = Auth::user(); $success['token'] = $user->createToken('AppName')->accessToken; return response()->json(['success' => $success], 200); } else { return response()->json(['error'=>'Unauthorised'], 401); } } public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'password_confirmation' => 'required|same:password', ]); if ($validator->fails()) { return response()->json([ 'error'=> $validator->errors() ]); } $data = $request->all(); $data['password'] = Hash::make($data['password']); $user = User::create($data); $success['token'] = $user->createToken('AppName')->accessToken; return response()->json(['success'=>$success], 200); } public function user_detail() { $user = Auth::user(); return response()->json(['success' => $user], 200); } } ?>
Step 9: Run The ApplicationWe can start the server and run this application using the below command.
php artisan serve
Read AlsoLaravel 7 CRUD Operation With Ajax Example
Laravel 7 Pagination Example Tutorial
Now, you can call the rest API using postman. so we shared some screenshot.Register Api
Login ApiUser Get Api
Download
Hope this code and post will helped you for implement Laravel 7 REST API With Passport Authentication Tutorial – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs