Your Essential Queries
How To Setup Laravel Passport
We'll See How To Setup Laravel Passport Easily:
1) Open Terminal
- cd /var/www/project__dir
2) Install Passport Package
- composer require laravel/passport
3) Migrate Auto Generated Tables for Passport
- php artisan migrate
4) Install Passport Keys
- php artisan passport:install
5) Use Passport HasApiTokens trait to User Model
- <?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 should be hidden for serialization.
- *
- * @var array
- */
- protected $hidden = [ 'password'];
- }
6) Use Passport Routes To AppServiceProvider
- <?php
- namespace App\Providers;
- use Illuminate\Support\ServiceProvider;
- use Illuminate\Support\Facades\Blade;
- use Laravel\Passport\Passport;
- class AppServiceProvider extends ServiceProvider
- {
- /**
- * Register any application services.
- *
- * @return void
- */
- public function register()
- {
- //
- }
- /**
- * Bootstrap any application services.
- *
- * @return void
- */
- public function boot()
- {
- Passport::routes();
- }
- }
7) Update Auth Drive in config/auth.php
- 'guards' => [
- 'web' => [
- 'driver' => 'session',
- 'provider' => 'users',
- ],
- 'api' => [
- 'driver' => 'passport',
- 'provider' => 'users',
- ],
- ],
Sample Code Using Passport for Login (routes/api.php):
- <?php
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Validator;
- use App\Models\User;
- Route::post('/user/login', function (Request $request) {
- $validator = Validator::make($request->all(),[
- 'email' => 'required',
- 'password' => 'required'
- ]);
- if($validator->fails()) {
- return response()->json($validator->errors(), 202);
- }
- if(Auth::attempt(['email'=>$request->email, 'password'=>$request->password])){
- $user = Auth::user();
- $res = [];
- $res['user'] = $user->name;
- $res['token'] = $user->createToken($user->name)->accessToken; //sending token with response
- return response()->json($res, 200);
- } else {
- return response()->json(['message'=>'Password not matched!']);
- }
- });
- Route::middleware('auth:api')->post('/user/details',function(){
- return response()->json(User::all());
- });