Laravel 8 Register and Login Rest API Using Passport. In this tutorial, you are going to learn of creating Register and Login restful API using Passport in Laravel 8. We will implement step by step Laravel Passport authentication with example.
The restful API is used to create a mobile application or you are developing a web application using Angular, React JS, or frontend language.
Laravel provides a simple way to build API. If your application is based on authentication then you can use Laravel Passport. Laravel Passport provides an authentication token to validate users.
The following are the steps to build the Laravel 8 Resister and login rest API using Passport:
- Laravel 8 installation
- Database Configuration
- Laravel Passport Installation
- Laravel Passport Configuration
- API Route Creation
- Controller Creation
- API testing Using Postman
1. Laravel Installation
Run the below mention command in the command prompt to install the new Laravel 8.
1 | composer create-project --prefer-dist laravel/laravel laravel8 |
2. Database Configuration
Navigate to your installed Laravel and open the .env file for setting the database.
1 2 3 4 5 6 | DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Enter Database name DB_USERNAME=Enter Database UserName DB_PASSWORD= Password of the database |
3. Laravel Passport Installation
Navigate to your created project and run the composer command to install the Laravel Passport package:
1 | composer require laravel/passport |
Due to the long migration unique key, you may get the below error when running the migration command so before it, you have to change the code:
1 | SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`)) |
Open the app/Providers/AppServiceProvider.php and add the below line of code:
1 2 3 4 5 6 | use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); } |
After installation of the Passport, some migration files have been generated in the database migration directory to store OAuth2 clients and access tokens to authenticate the application. So simply run the below command:
1 | php artisan migrate |
Next, run the below command to create the encryption keys for generating secured access tokens:
1 | php artisan passport:install |
4. Passport Configuration
In this step, open the User.php file which is in App/Models directory, and update the following code inside the 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', ]; } |
Next Register passport routes in App/Providers/AuthServiceProvider.php, open App/Providers/AuthServiceProvider.php and update this code Passport::routes(); inside of boot method:
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 | <?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate; use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ // 'App\Models\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); } } |
Next, Navigate to config/auth.php and open the auth.php file. Then change the API driver to the session to passport. Put this code ‘driver’ => ‘passport’, in API :
1 2 3 4 5 6 7 8 9 10 11 12 | 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', 'hash' => false, ], ], |
5. API Route Creation
Open api.php file from route directory and add the following code to login, register, and get the user details:
1 2 3 4 5 6 7 8 | use App\Http\Controllers\Api\UserController; Route::post('login', [UserController::class, 'login']); Route::post('register', [UserController::class, 'register']); Route::group(['middleware' => 'auth:api'], function(){ Route::post('user-details', [UserController::class, 'userDetails']); }); |
6. Controller Creation
You need to create a controller name UserController using below the command:
1 | php artisan make:controller Api\UserController |
After that, add the following code:
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 | <?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Auth; use Validator; class UserController extends Controller { public $successStatus = 200; /** * login api * * @return \Illuminate\Http\Response */ public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $success['token'] = $user->createToken('MyLaravelApp')-> accessToken; $success['userId'] = $user->id; return response()->json(['success' => $success], $this-> successStatus); } else{ return response()->json(['error'=>'Unauthorised'], 401); } } /** * Register api * * @return \Illuminate\Http\Response */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required', 'c_password' => 'required|same:password', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $success['token'] = $user->createToken('MyLaravelApp')-> accessToken; $success['name'] = $user->name; return response()->json(['success'=>$success], $this-> successStatus); } /** * details api * * @return \Illuminate\Http\Response */ public function userDetails() { $user = Auth::user(); return response()->json(['success' => $user], $this-> successStatus); } } |
In the resister API, validating email that should be unique, checking password and confirm password, those should be the same.
7. Laravel Rest API testing Using Postman
Run the application using the below command to see Laravel 8 Register and Login Rest API Using Passport from the postman.
1 | php artisan serve |
- Register Rest API: To register a user, send a POST HTTP request (http://127.0.1.1:8000/api/register) and enter the name, email, password, c_password with appropriate details:
- Login Rest API: Once the registration is successful, you can run this POST HTTP request http://127.0.1.1:8000/api/login and enter your registered email and password to get authentication:
- User Detail API: To get the logged-in user details, run POST HTTP request() and copy the value of the token from login API response and pass in the Headers like below:
Authenticate: Bearer <token>
Accept: application/json
Conclusion:
In this tutorial, we have learned Laravel 8 Register and Login Rest API Using Passport. We have set up Laravel and Passport, Created Register and Login APIs, and get the data based on the logged-in user from the token. We have tested the Register and Login APIs using Postman.
You can download the code from Github.
You can visit Laravel’s official site to get more information About Laravel Passport.
method createToken is not defined..
Please follow step Laravel Passport Configuration