Home > OS >  How to login with laravel passport in seeder file?
How to login with laravel passport in seeder file?

Time:09-19

On laravel backend API site with passport I use service for data crud operations and inside of this service I use Auth::user() to fill creator of data.

Testing this service in POSTMAN I use oauth/token with client_id, client-secret, username, password parameters and it works ok. I need to add some init data in seeders using the same service

Looking how oauth/token at docs https://laravel.com/docs/9.x/passport

I added to my seeder:

use Illuminate\Support\Facades\Http;
 ...
$response = Http::asForm()->post(url('oauth/token'), [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => 'username',
    'password' => 'password',
    'scope' => '',
]);
 
\Log::info($response->json()); // I can see valid response
if(Auth::user()) { // that condition did not true
    \Log::info(Auth::user());
}

Which action have I to take to login with valid token? When I refer Auth::user()->id in service I got error :

Attempt to read property "id" on null

I tried to debug by routes outpout:

.token › Laravel\Passport › AccessTokenController@issueToken
  POST            oauth/token/refresh ........................................................................................................................ passport.token

file src/Http/Controllers/AccessTokenController.php

but I see only token functionality...

    "laravel/framework": "^9.2",
    "laravel/passport": "^10.3",

Thanks in advance!

CodePudding user response:

You can use Auth::loginUsingId() for user information that you want get

  • Related