php - Login route to use custom guard when default guard is set to 'api'

531

I am about to start building a gateway app that will be communicating with mobile app users exclusively via api. The gateway app also has the moderator users which are separated in a different table as moderators will only be using web interface and not api, to manage mobile users. I have set up the default guard as:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

and the rest of the stuff there:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'moderators',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

     'moderators' => [
         'driver' => 'eloquent',
         'model' => 'App\Moderator::class',
     ],
],

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],

   'moderators' => [
        'provider' => 'moderators',
        'table' => 'password_resets',
        'expire' => 15,
    ],
],

Now, the issue is that even with other guards set up correctly, the login route is always trying to use the default guard, no matter what I do and returns an error when I try to log in as a moderator.

I have specified$this->middleware('auth:web'); in controller, but it still uses default guard for login.

The idea is that mobile users will never be able to log in via web interface and only can communicate via api, and moderators will only use web guard and never api.

I could put default guard as 'web' and reverse the logic, but I still would like to know whether it is possible and how to make it work when default guard is set to 'api'.

718

Answer

Solution:

In case you are using grouped routes -

Route::middleware(['auth:api'])

In case you have ungrouped routes -

$this->middleware('auth:web')

People are also looking for solutions to the problem: PHP Warning: include(): Failed opening

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.