Laravel 9: User not authenticated on API routes using custom guard - laravel

I need to authenticate temporary users of a third party app. In addition, users only get a signed URL to login (there is no username/password). The temporary users get created on the fly and logged in after verifying the signed URL and some query params. Because I also have "traditional" users in my app I am using an additional database table called "clients", an additional provder 'clients' and an additional guard called 'vcs' for the authentication workflow.
The authentication workflow (user clicks on the signed URL, a new Client is created and saved to the database as well as logged in as new user) is working fine. The session is created correctly and send to the browser in the laravel_session cookie. The problem is, that all subsequent requests to my API seem to be unauthenticated.
config/auth.php:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'vcs' => [
'driver' => 'session',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Models\Client::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
My client model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Client extends Authenticatable
{
use HasFactory, HasApiTokens;
protected $guard = "vcs";
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'uuid';
/**
* Indicates if the model's ID is auto-incrementing.
*
* #var bool
*/
public $incrementing = false;
protected $keyType = 'string';
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'uuid';
}
}
The clients get a signed URL which points to the following controller action. The action checks for a valid query parameter in the URL (simplified for this thread). After that a new Client model gets created and the new Client gets logged in using the 'vcs' guard:
<?php
namespace App\Http\Controllers\VCS;
use Illuminate\Http\Request;
use App\Models\Client;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function redirectWithCookie(Request $request)
{
// reduced for the sake of simplicity here
$credential = $request->someURLParameter;
if ($credential) {
$client = new Client;
$client->uuid = Str::uuid()->toString();
$client->ip = $request->ip();
$client->status = 'pending';
$client->save();
Auth::guard('vcs')->login($client, $remember = true);
// this logs the authenticated user correctly!
Log::info('Authenticated User: ' . Auth::guard('vcs')->user());
$cookieValue = json_encode(array('uuid' => $client->uuid));
$cookie = cookie('mycookie', $cookieValue);
$redirectUrl = config('my.redirect.url');
return redirect()->away($redirectUrl)->withCookie($cookie);
}
return response(['message' => 'Invalid URL', 'error' => 'url'], 422);
}
}
routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\VCS\AuthController;
Route::get('/', function () {
return ['Laravel' => app()->version()];
});
Route::get('vcs/auth', [AuthController::class, 'redirectWithCookie'])->name('vcs.auth');
require __DIR__.'/auth.php';
routes/api.php:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\VCS\RoomController;
Route::middleware(['auth:sanctum'])->get('/user', function (Request $request) {
return $request->user();
})->name('profile');
Route::middleware(['auth:vcs'])->group(function () {
Route::get('rooms', [RoomController::class, 'rooms']);
});
After the redirect I get a laravel_session as a cookie which should authenticate my subsequent requests. The problem is that I can't call any API routes with the custom guard and I am not authenticated anymore although the browser is sending my session cookie with the request. For example calling the /api/rooms GET-endpoint defined in the api.php results in a redirect to the login page.
I also see that the user is not authenticated in the auth-middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
Log::info('Authenticated User: ' . Auth::guard('vcs')->user());
}
}
The Log just returns an empty string so the user is not authenticated:
[2022-11-06 13:44:30] local.INFO: Authenticated User:
So my question is: How can I use a custom guard for my API routes after manually logging new users in?
I also tried the same workflow using Insomnia as a REST Client:
Login by URL:
whichs gives me a sessions cookie.
Access some API Route:
Which results in an Unauthorized-Status-Code..

Related

Laravel authentication login keeps giving "These credentials do not match our records."

I have setup laravel and used it's default authentication controller but I modified the table name and it's table structure and accordingly I also changed the RegisterController and LoginController. And the RegisterController is working fine and registering a new user but when ever I try to login using the login form it gives the same validation error of "These credentials do not match our records."
I have attached the following files: LoginController, RegisterController, Admin(Model), Config->auth
I have overridden the username field according to my EmailAddress field.
Admin Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class admin extends Authenticatable
{
use Notifiable;
public $table = 'admin';
public $timestamps = false;
protected $primaryKey = 'AdminId';
protected $fillable = ['FirstName', 'LastName', 'FirstName_ar','LastName_ar','EmailAddress','Password','IsActive','remember_token'];
protected $hidden = ['Password', 'remember_token'];
public function getAuthPassword()
{
return $this->Password;
}
}
Login Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'EmailAddress';
}
public function getRememberTokenName()
{
return "remember_token";
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|string|max:255',
'lastname' => 'required|string|max:255',
'firstname_ar' => 'required|string|max:255',
'lastname_ar' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return admin::create([
'FirstName' => $data['firstname'],
'LastName' => $data['lastname'],
'FirstName_ar' => $data['firstname_ar'],
'LastName_ar' => $data['lastname_ar'],
'EmailAddress' => $data['email'],
'Password' => bcrypt($data['password']),
'IsActive' => 1,
'remember_token' => str_random(10)
]);
}
public function getRememberTokenName()
{
return $this->remember_token;
}
}
Config->auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'admin',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'admin' => [
'driver' => 'eloquent',
'model' => App\admin::class,
],
],
'passwords' => [
// 'users' => [
// 'provider' => 'users',
// 'table' => 'password_resets',
// 'expire' => 60,
// ],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
];
In the RegisterController, in the create method, instead of
'password' => bcrypt($data['password']), do this
'password' => Hash::make($data['password'])
Probably why your error is happening because maybe when you're registering you're using the bcrypt hashing method for the password but when you're logging, it's using a different hashing method.
Make sure to import the class
use Illuminate\Support\Facades\Hash;
at the top of your RegisterController file.
One more thing to take care of here is to make sure when you're inserting the new user record in the database, make sure to lowercase the email by default and when logging, make sure to lowercase the email too. Some databases are case sensitive by default. So you may have a problem there.
Like you have an email in the database,
Admin#example.com and when logging, you give admin#example.com, it will not match in that case.
Hope this helps.

custom auth of two different users using two tables. i don't want to use make:auth

The first auth system works very fine its code is below and needed to have to different users using two different tables am using laravel 5.5
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class StudentController extends Controller
{
public function Register(Request $request)
{
$firstname = $request['firstname'];
$othername = $request['othername'];
$email = $request['email'];
$password = $request['password'];
$user = new User();
$user->firstname = $firstname;
$user->othername = $othername;
$user->email = $email;
$user->password = $password;
$user->save();
Auth::login($user);
return redirect()->route('studentDashboard');
}
public function Login(Request $request)
{
if(Auth::attempt(['email'=> $request['email'], 'password'=>
$request['password']]))
{
return redirect()->route('studentDashboard');
}
return redirect()->back();
}
}
i duplicated the above to create auth for a different user.The registration works but the login does not work even if the login data is right it returns the redirect back after the if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employer;
use Illuminate\Support\Facades\Auth;
class EmployerController extends Controller
{
public function createEmployerAccount(Request $request)
{
$companyName = $request['companyname'];
$companyEmail = $request['email'];
$companyPasword = $request['password'];
$Employer = new Employer();
$Employer->companyname = $companyName;
$Employer->email = $companyEmail;
$Employer->password = $companyPasword;
$Employer->save();
Auth::login($Employer);
return redirect()->route('employersDashboard');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
when i try to change the 'email' to 'emails' an error is shown->the select query is from the users table not employers table that i need to get data from and also when i change 'password' to 'passwords' an error "undefined index password" is shown
this is the route file content
Route::get('/',function(){
return view('pages.index');
})->name('home');
Route::post('/signup',[
'uses'=>'StudentController#Register',
'as'=> 'signup'
]);
Route::post('/signin',[
'uses'=>'StudentController#Login',
'as'=>'signin'
]);
Route::get('/employers',[
'uses'=>'PageController#employersPage',
'as'=>'employers'
]);
Route::get('/studentDashboard',[
'uses'=>'PageController#getStudentDashboard',
'as'=> 'studentDashboard'
]);
Route::post('/createcompany',[
'uses'=>'EmployerController#createEmployerAccount',
'as'=>'createcompany'
]);
Route::post('/signInEmployer',[
'uses'=>'EmployerController#signInEmployer',
'as'=>'signInEmployer'
]);
Route::get('/employersDashboard',[
'uses'=>'PageController#getEmployersDashboard',
'as'=> 'employersDashboard',
'middleware'=>'auth:employer'
]);
Route::post('/createPost',[
'uses'=>'PostController#postCreatePost',
'as'=> 'createPost'
]);
You need to tell Auth to use different Guard for authentication at time of Employer login. To define guards for Employer change like this in your config/auth.php.
Look for guards section in auth.php and add your new guard
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'employer' => [
'driver' => 'session',
'provider' => 'employers',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Now in the same file there is a providers section. You need to add employers provider
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
//Employer provider
'employers' => [
'driver' => 'eloquent',
'model' => App\Employer::class,
],
],
Create a custom Auth middleware
namespace App\Http\Middleware;
use Closure;
use Auth;
class AuthenticateEmployer
{
public function handle($request, Closure $next)
{
//If request does not comes from logged in employer
//then he shall be redirected to employer Login page
if (!Auth::guard('employer')->check()) {
return redirect('/signInEmployer');
}
return $next($request);
}
}
Register custom auth middleware in Kernal.php in routeMiddleware
'employerAuth' => \App\Http\Middleware\AuthenticateEmployer::class,
Now we have setup our custom guard and custom middleware employerAuth
EmployerController
class EmployerController extends Controller
{
//either you have to define this or you can use `Auth::guard('employer')->attempt($credentials)` in login
protected function guard()
{
return Auth::guard('employer');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
For all the routes protected by Employer auth, you either need to add middleware employerAuth in routes or add employerAuth in each controller construct like this
public function __construct()
{
$this->middleware('employerAuth');
}
Hope it may help you. For details you can check this https://laravel.com/docs/5.6/authentication#authenticating-users
Check this nice sample app for multi auth application https://github.com/yskoverride/Various2.0/tree/master/app

RequestGuard::attempt does not exist

I am trying multiguard authentication for api when i login for admin i am getting
following error
BadMethodCallException
Method Illuminate\Auth\Req
uestGuard::attempt does not exist.
here is my login method in controller
public function login(Request $request){
if(Auth::guard('admin-api')->attempt(['email' => request('email'), 'password' => request('password')]))
{
// if successful, then redirect to their intended location
$user = Auth::guard('admin-api');
$success['token'] = $user->createToken('admin')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
my api.php
Route::prefix('admin')->group(function () {
Route::post('login', 'API\Admin\AdminController#login')->name('admin.login');
Route::post('register', 'API\Admin\AdminController#register')->name('admin.register');
Route::group(['middleware' => 'auth:admin-api'], function(){
Route::post('get-details', 'API\Admin\AdminController#getDetails');
});
});
my admin model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $table = 'admin';
protected $guard = 'admin-api';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
please tell me any other inputs you want
A better hack is this
$credentials = ['email' => $request->username, 'password' => $request->password];
//Since we are not using guard web in API request, we have to add it here (
// guard('web') ) to access the Auth::attempt function,
// the Auth::attempt needs web guard and crsf token, but using it here bypasses
// the post with crsf.
if (Auth::guard('web')->attempt($credentials, false, false)) {
dd('user is OK');
}else{
dd('user is NOT OK');
}
Unfortunately the Laravel Facade for Auth does not expect you to use it for the api guard since sessions and cookies will be set, Thus does not support ->attempt() function. But the API middle-ware disables session and cookies since it is stateless. So here is the hack.
Get to your confi\auth and create a similar web instance for your api guards thus
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'drivers-web' => [
'driver' => 'session',
'provider' => 'drivers',
],
'api' => [
'driver' => 'passport',//previously "token"
'provider' => 'users',//This will be switched regularly from the middleware between drivers and users
],
'drivers-api' => [
'driver' => 'passport',//previously "token"
'provider' => 'drivers',
],
],
Never the less, You can use passport to generate your client access tokens which are stateless sessions. And also serve well for authentication.
you cannot use Auth::guard('admin-api')->attempt with a guard with driver value is token or passport so you can repeat the guard and make one with session driver and the second one with passport then you can use the session one to make difference between earch other you can see a reference and source code from here https://web-brackets.com/discussion/103/method-illuminate-auth-requestguard-attempt-does-not-exist-
To me, I changed drivers for the web from passport to session. Laravel's cache had to be cleared to be able to go back to the session driver
php artisan cache:clear

creating a custom authentication system in laravel

How can I build an authentication system for customer?
I have used laravel built in authentication system for my admin panel where built in user model and users table already used.
Now I want to build another authentication system for my customer where customer model and customers table will be used.
How can I do this in laravel 5.2 ?
How to implement Multi Auth in Larvel 5.2
As Mentioned above. Two table admin and users
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()
Edit - 1
We can access authenticated user directly using
Auth::user() but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()

How to Create Multi Auth in Laravel 5.2

I have made multi auth but i have problem with final code. I have code like this
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
And what does this code mean Auth::guard('admin')->user() ? And where must i type that code?
And what does this code mean Auth::guard('admin')->user() ?
In simple word, Auth::guard('admin')->user() is used when you need to get details of logged in user. But, in multi auth system, there can be two logged in users (admin/client). So you need to specify that which user you want to get. So by guard('admin'), you tell to get user from admin table.
Where must i type that code?
As from answer, you can understand that where must you use it. But still I can explain with example. Suppose there are multiple admins. Each can approve users request (like post/comments etc). So when an admin approve any request, then to insert id of that admin into approved_by column of post, you must use this line.

Resources