Laravel 9 - ERROR: Auth guard [ admin] is not defined - laravel

I'm trying to create an Admin Login in Laravel Jetstream. I've created a separate admins table to store the login data. However, I get an error saying Auth guard [ admin] is not defined when I try to access the admin login page through http://localhost:8000/admin/login.
I tried php artisan config:clear and php artisan config:cache commands, but they didn't solve the issue.
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
web.php
Route::get('/', function () {
return view('welcome');
});
Route::group(['prefix' => 'admin', 'middleware' => ['admin:admin']], function () {
Route::get('/login', [AdminController::class, 'loginForm']);
Route::post('/login', [AdminController::class, 'store'])->name('admin.login');
});
Route::middleware(['auth:sanctum, admin', config('jetstream.auth_session'), 'verified'])->group(function () {
Route::get('/admin/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Route::middleware(['auth:sanctum, web', config('jetstream.auth_session'), 'verified'])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
AdminController
public function loginForm()
{
return view('auth.login', ['guard' => 'admin']);
}
AdminRidirectIfAuthenticated.php
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect($guard . '/dashboard');
}
}
return $next($request);
}
LoginResponse.php
public function toResponse($request)
{
return $request->wantsJson()
? response()->json(['two_factor' => false])
: redirect()->intended('admin/dashboard');
}
Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'admin' => \App\Http\Middleware\AdminRedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
FortifyServiceProvider.php
use App\Http\Controllers\AdminController;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Support\Facades\Auth;
use App\Actions\Fortify\AttemptToAuthenticate;
use App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable;
public function register()
{
$this->app->when([AdminController::class, AttemptToAuthenticate::class, RedirectIfTwoFactorAuthenticatable::class])
->needs(StatefulGuard::class)
->give(function () {
return Auth::guard('admin');
});
}
login.blade.php
<form method="POST" action="{{ isset($guard) ? url($guard.'/login') : route('login') }}">
#csrf
..............
</form>
AdminStatefulGuard.php
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
interface AdminStatefulGuard extends Guard
{
/**
* Attempt to authenticate a user using the given credentials.
*
* #param array $credentials
* #param bool $remember
* #return bool
*/
public function attempt(array $credentials = [], $remember = false);
/**
* Log a user into the application without sessions or cookies.
*
* #param array $credentials
* #return bool
*/
public function once(array $credentials = []);
/**
* Log a user into the application.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param bool $remember
* #return void
*/
public function login(Authenticatable $user, $remember = false);
/**
* Log the given user ID into the application.
*
* #param mixed $id
* #param bool $remember
* #return \Illuminate\Contracts\Auth\Authenticatable|bool
*/
public function loginUsingId($id, $remember = false);
/**
* Log the given user ID into the application without sessions or cookies.
*
* #param mixed $id
* #return \Illuminate\Contracts\Auth\Authenticatable|bool
*/
public function onceUsingId($id);
/**
* Determine if the user was authenticated via "remember me" cookie.
*
* #return bool
*/
public function viaRemember();
/**
* Log the user out of the application.
*
* #return void
*/
public function logout();
}

Remove space before middleware parameter at web.php
Remove space before admin at 'auth:sanctum, admin'

Related

use laravel jwt authentication only for api without affecting web

I have an issue with authentication in laravel web, I only what to use the JWT authentication for the api only, I notice whenever I change guard in defaults to web 'guard' => 'web' and I try to login with postman using my api it will not work and this error show("message": "Method Illuminate\Auth\SessionGuard::factory does not exist.") but the web will work, if I change it to 'guard' => 'api' I will not be able to login in the web but the api postman login will work.
Only web will work
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Only api will work
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Route
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);
Route::post('refresh', [AuthController::class, 'refresh']);
Route::post('me', [AuthController::class, 'me']);
});
Controller
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
public function me()
{
return response()->json($this->guard()->user());
}
public function logout()
{
$this->guard()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
public function refresh()
{
return $this->respondWithToken($this->guard()->refresh());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => $this->guard()->factory()->getTTL() * 60
]);
}
public function guard()
{
return Auth::guard();
}
}
I just want to use JWT authentication for only the api without affecting the web, Thanks
What defaults.guard config does is setting the default guard to be used if none specified.
If you want 2 different authentication methods and guards you should specify each by name in your middlewares.
So instead of Route::middleware('auth')->get(...);
you should write Route::middleware('auth:api')->get(...);
If you want to protect all routes in a group you can do it in app/Http/Kernel.php by adding this lines:
protected $middlewareGroups = [
'web' => [
...
'auth:web'
],
'api' => [
...
'auth:api'
],
];
you can use this
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
and in controller where you need api guard use this
auth('api')
for example in login controller
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (!$token = auth('api')->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$token = auth('api')->claims(['user' => auth('api')->user()])->attempt($validator->validated());
return $this->createNewToken($token);
}
i use this controller and works for me
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (!$token = auth('api')->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$token = auth('api')->claims(['user' => auth('api')->user()])->attempt($validator->validated());
return $this->createNewToken($token);
// return response()->json([
// 'token' => $this->createNewToken($token),
// ]);
}
/**
* Register a User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user,
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
Auth::logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->createNewToken(auth::refresh());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function userProfile()
{
return response()->json(auth::user());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60,
'user' => auth('api')->user(),
]);
}
}
and routes
Route::prefix('user')->middleware('api')->group(function () {
Route::post('/login', [UserController::class, 'login']);
Route::post('/logout', [UserController::class, 'logout']);
Route::post('/refresh', [UserController::class, 'refresh']);
Route::get('/user-profile', [UserController::class, 'userProfile']);
Route::post('/register', [UserController::class, 'register']);
});

Cannot Access user profile using JWT in Laravel

I have used JWT in Laravel for user Authentication
Auth Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
}
return $this->createNewToken($token);
}
/**
* Register a User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function register(Request $request) {
$messages = [
'password.confirmed' => 'Password Confirmation should match the Password',
'password.min' => ' Password should be minimum 6 digits',
];
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
],$messages);
if($validator->fails()){
return response()->json($validator->errors(), 422);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'Successfully registered',
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh() {
return $this->createNewToken(auth()->refresh());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function userProfile() {
return response()->json(auth()->user());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
}
routes :
Route::group([
'middleware' => ['api'],
'prefix' => 'auth'
], function ($router) {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/refresh', [AuthController::class, 'refresh']);
Route::get('/user-profile', [AuthController::class, 'userProfile']);
Login and register is working
but when i access user-profile route getting this error :
Symfony\Component\Routing\Exception\RouteNotFoundException: Route
[login] not defined. in file
C:\wamp64\www\project\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php
on line 420
and i cannot get id of user if some user is logged in using : auth()->user()->id
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'users',
],
],
Model :
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
#use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{ #HasFactory,
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'otp',
'user_verification_token',
'verified',
'token',
'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims() {
return [];
}
}
Any suggestion is highly appreciated
Thanks
Error message says there is no route that named as 'login'
Route::post('/login', [AuthController::class, 'login'])->name('login');

Laravel 5.8: Multi users authentication issue

in my laravel project, I have two users (Admins and Users).
I got started admins' authentification.
Now when I go to a create page (http://127.0.0.1:8000/admin/posts/create) in my CRUD application, it redirects to http://127.0.0.1:8000/login.
I am glad if someone gives me a solution to go back to http://127.0.0.1:8000/admin/login page which is admin side login page.
Here is my codes.
web.php
Route::prefix('admin')->group(function(){
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.dashboard');
Route::resource('categories','CategoriesController');
Route::resource('posts', 'PostsController')->middleware('auth');
Route::get('trashed-posts', 'PostsController#trashed')->name('trashed-posts.index');
Route::PUT('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
});
VerifyCategoriesCount.php in my middleware folder
public function handle($request, Closure $next)
{
if (Auth::check()) {
if (Auth::user()->role == 'Admin') {
return $next($request);
}
}
return redirect('/admin/');
}
kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'verifyCategoriesCount' => VerifyCategoriesCount::class
];
postsController.php
public function __construct()
{
$this->middleware('VerifyCategoriesCount')->only('store');
$this->middleware('admin')->except('index');
}
Add an admin guard in auth.php
'admin' => [
'driver' => 'session',
'provider' => 'admins', //table name
],
And add providers array
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class, //Bind your Admin Model
],
Add two middleware,
class AdminRedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::guard('admin')->check()) {
return redirect('/admin/home');
}
return $next($request);
}
}
And
class AdminRedirectIfNotAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::guard('admin')->check()) {
return redirect('/admin/login');
}
return $next($request);
}
}
Register your middlewares in kernel.php
'admin.auth' => \App\Http\Middleware\AdminRedirectIfNotAuthenticated::class,
'admin.guest' => \App\Http\Middleware\AdminRedirectIfAuthenticated::class,
In your AdminController.php add,
public function __construct()
{
$this->middleware('admin.auth');
}
And,
In your LoginController.php add,
public function __construct()
{
$this->middleware('admin.guest');
}
In web.php
Route::get('/admin/login', 'Admin\LoginController#showLoginForm')->name('admin.login');
Route::get('/admin/home', 'Admin\AdminController#home')->name('home');

How to create multi auth in laravel 5.6?

I used to be for laravel 5.5 and earlier than https://github.com/Hesto/multi-auth .
But this repository don't update for laravel 5.6.
How to create multi auth in Laravel 5.6?
After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.6 Multi Auth with two table, So I'm writing Answer of my own Question.
How to implement Multi Auth in Larvel
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()
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