How do I find which `guard` made the current request in Laravel?

Active3 hr before
Viewed126 times

7 Answers


Get all the guards defined in the application and find which of them the current user logged in with., Meta Stack Overflow ,Asking for help, clarification, or responding to other answers.,Connect and share knowledge within a single location that is structured and easy to search.

Unfortunately, there is not an existing function to actually get the name of the guard. You can use auth()->guard()->getName() but that returns the session identifier for the guard (i.e. login_guardname_sha1hash) but if you need it you can extract it:

$guard = auth() - > guard(); // Retrieve the guard
$sessionName = $guard - > getName(); // Retrieve the session name for the guard
// The following extracts the name of the guard by disposing of the first
// and last sections delimited by "_"
$parts = explode("_", $sessionName);
unset($parts[count($parts) - 1]);
$guardName = implode("_", $parts);
load more v

Authentication ,Social Authentication,Stateless HTTP Basic Authentication,Manually Authenticating Users Remembering Users Other Authentication Methods

Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

php artisan make: auth
load more v

Multiple authentications make it possible for you to direct different classes of users to differing parts of the same application.,Now, let us look at how to create multiple authentications for our different classes of users.,There are many reasons why you may want to use multiple authentications in your Laravel application. For example:,The rest of the company: these roles can be split up to represent different functions with different duties and administrative allowances.

We need to create a new Laravel application. Run the following command on your terminal to create a new Laravel application:

    $ laravel new multi - auth
    $ cd multi - auth
load more v

php artisan make: middleware BasicAuth //In console.

   //BasicAuth.php file is created:
   ? php
namespace App\ Http\ Middleware;

use Closure;
use Illuminate\ Support\ Facades\ Auth;

class AdminAuth {
    * Handle an incoming request.
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
   function handle($request, Closure $next) {
      return $next($request);

//Replace handle function:
function handle($request, Closure $next) {
   //The following line(s) will be specific to your project, and depend on whatever you need as an authentication.
   $isAuthenticatedAdmin = (Auth::check() && Auth::user() - > admin == 1);

   //This will be excecuted if the new authentication fails.
   if (!$isAuthenticatedAdmin)
      return redirect('/login') - > with('message', 'Authentication Error.');
   return $next($request);

//In app/Http/Kernel.php, add this line:
protected $routeMiddleware = [
    * All the laravel-defined authentication methods
   'adminAuth' => \App\ Http\ Middleware\ AdminAuth::class //Registering New Middleware

//In routes/web.php, add this at the end of the desired routes:
Route::get('/adminsite', function() {
   return view('adminsite');
}) - > middleware('adminAuth'); //This line makes the route use your new authentication middleware.

The best way to do this, in my opinion, is to create a middleware that we can apply to our API routes.,Create the middleware php artisan make:middleware UseApiGuard,Add the middleware to your app/Http/Kernel.php file,This is because my API routes used the api guard to authenticate, and as I hadn't specified otherwise, $request->user() was trying to resolve the user using the web guard.

When using the $request object to resolve a user through $request->user(), as no guard has been passed into user(), Laravel will use the default web guard. This works perfectly fine for any of your web routes, as this is what is being used by default:

 1 // Controller method for a web route 2  3public function store(Request $request) 4{ 5    // Your store logic... 6  7    // Old way I was using 8    $user = Auth::user(); // Returns currently authenticated user 9 10    // New way11    $user = $request->user(); // Returns currently authenticated user12}
load more v

When developing a web application, it is generally a good idea to split it into two tiers. A middle-tier API interacts with the database, and a web tier usually consists of a front-end SPA or MPA. This way, a web application is more loosely coupled, making it easier to manage and debug in the long run.,When the API has been created, setting up authentication and state in a stateless API context might seem somewhat problematic.,Now we want to create the authentication controller with login and register functions.,Now, to add Laravel API authentication for our users, we are going to create login, logout, and register (signup) functions in the same file.

  • PHP 7+, MySQL, and Apache (developers wanting to install all three at once can use XAMPP.)
  • Composer
  • Laravel 7
  • Laravel Passport. Since APIs are generally stateless and do not use sessions, we generally use tokens to keep state between requests. Laravel uses the Passport library to implement a full OAuth2 server we can use for authentication in our API.
  • Postman, cURL, or Insomnia to test the API—this is up to personal preference
  • Text editor of your choice
  • Laravel helpers (for Laravel 6.0 and up)—after installing Laravel and Passport, just run:
composer require laravel / helpers
load more v

Finally, for your application to be ready to use Passport’s TokenGuard,This will give you an idea of all the routes for our application.,After registering Passport::routes(), Laravel Passport is almost ready to handle all authentication and authorization processes within your application.,The database is all set, but before we start building our API, we need to install and configure Laravel Passport.

$ laravel new laravel - backend - api
load more v

Other "undefined-undefined" queries related to "How do I find which `guard` made the current request in Laravel?"