skip to Main Content

Here is an example of Laravel command:

class TestUserCommand extends Command
{
    protected $signature = 'test:user';

    protected $description = 'Command description';

    public function handle(): void
    {
        auth('api')->loginUsingId(1);

        ... domain service call
    }
}

It gives me the following error:

 Method IlluminateAuthRequestGuard::loginUsingId does not exist.

What I want to do is authenticate so I can then initiate some complex business logic, that internally retrieves current user like so:

return auth('api')->check() ? auth('api')->user() : null;

Here is my auth.php configuration:

   'guards' => [
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

UPD: What worked for me as temporary solution is Passport::actingAs(), but it does not seem to be meant for production.

2

Answers


  1. loginUsingId does not exists on the RequestGuard, that’s a method on the SessionGuard and you are using api auth here, in that case it won’t work. Better you use web auth instead of api in your case, please try below code:

    use Auth;
    
    class TestUserCommand extends Command
    {
        protected $signature = 'test:user';
    
        protected $description = 'Command description';
    
        public function handle(): void
        {
            Auth::loginUsingId(1);
    
            ... domain service call
        }
    }
    

    and to check if you are authenticated or not, try this:

    return Auth::check() ? Auth::user() : null;
    
    Login or Signup to reply.
  2. Try with Auth::attempt() and use prompt to get mail and password like,

    public function handle() {
        $email = $this->ask('Email ?');
        $password = $this->secret('Password ?');
    
        $attempt = Auth::attempt(['email' => $email, 'password' => $password]);
        if($attempt) {
            $user = auth()->user();
        }
    }
    

    Otherwise with Arguments like,

    protected $signature = 'test:user {email} {password}';
    // php artisan test:user [email protected] secret
    

    Inside handle method, you will get inputs with argument method

    $email = $this->argument('email');
    $password = $this->argument('password');
    

    Hope this may help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search