Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the default guard on a route group

Tags:

php

laravel

I have set up an API token for my users which they can optionally provide when accessing API routes for additional data to be returned.

This is my auth.php configuration:

'defaults' => [
    'guard' => 'web',      
],    
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'eloquent',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'eloquent',
    ],
],

I have various (shared) places in my code which use checks like $request->user() without providing the guard. The problem is that this always uses the default guard.

However if I set one of the API routes as to use middleware auth:api then it uses the api guard by default as I'd expect. I can't really set that up though because as I mentioned, authentication is optional and using the auth middleware makes it mandatory.

I'm wondering if there's a way to set all API routes such that their default guard is the API guard.

like image 636
apokryfos Avatar asked Mar 02 '18 14:03

apokryfos


People also ask

How do I change my default Guard in Laravel?

By default, web routes are configured to use the web guard and API routes are configured to use the api guard, and unless otherwise specified, Laravel will use the web guard by default. This is specified in your config/auth. php file and you are free to change this as needed.

What does a namespace Route Group allow?

Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.

What is Auth guard in Laravel?

At its core, Laravel's authentication facilities are made up of "guards" and "providers". Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies.


1 Answers

For me the easiest was to add to the Api\Controller (The one that extends all your classes), the following line:

public function __construct()
{
    // We set the guard api as default driver
    auth()->setDefaultDriver('api');
}
like image 52
Eduardo Alonso Avatar answered Sep 28 '22 05:09

Eduardo Alonso