Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Desssha's avatar

Middleware Not work !!

Hello please can explain me why it happedned . i hve make middleware and was work ok but suddenly stop and redirect me any way problem in method where Authenticate .php

 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)
    {

        if (! $request->expectsJson()) {
            return route('login');
        }
    }
} 

this return me to login if i logged not allow for user he have permisson to go this middleware

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()){
            if (Auth::user()->user_type == 1){  //Any Manger Can Access only Not Users
                return $next($request);
            }else{
              return redirect()->back();
//            abort(403);
            }
        }else{
            return redirect()->back();
        }

    }

}

and user_type == 1 was try in middle ware dd(Auth::user()); but if put it in side method redirectTo

dd(Auth::user()); return info bout user but not return nothing direct go to login in Authenticate ,

Route::group(['middleware' => 'auth:admin'], function () {

Route::get('admin/dashboard', function () {
    return view('admin.index');
})->name('admin.dashboard');

and befor it was work ok . what problem !

0 likes
27 replies
furqanDev's avatar

You are using auth middleware and passing admin as the tag. You are not using your newly created middleware. In your auth middleware,

if (!$request->expectsJson()) {
	if ($request->routeIs('admin.*')) {
		return route('admin.login');
}
	return route('login');
}
furqanDev's avatar

@Desssha Try Again with this

if (!$request->expectsJson()) {
	if ($request->routeIs('admin/*')) {
		return route('admin.login');
}
	return route('login');
}
Desssha's avatar

@furqanDev return me back again to user dashboard can't access admin dashboard . and i need middleware to save this route . why middleware not work !!!!!!!!

Desssha's avatar

@furqanDev not feel middleware i try dd(Auth::user()); not feel it not give any info , why not look in middleware first !!

furqanDev's avatar

@Desssha If you have set this middleware in your kernel.php file the you are not applying it to the routes.

Route::group(['middleware' => ['auth:admin', 'your-middleware']], function () {

Route::get('admin/dashboard', function () {
    return view('admin.index');
})->name('admin.dashboard');
Desssha's avatar

@furqanDev Route::group(['middleware' => ['auth', 'admin']], function () {

Route::get('admin/dashboard', function () { return view('admin.index'); })->name('admin.dashboard'); also the same first or Route::group(['middleware' => ['auth:admin', 'admin']], all the sam and try it before can't access this route middleware protect but not allow for user who user_type == 1

Desssha's avatar

@furqanDev i dd and not back anyhing .

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
//    public const HOME = '/dashboard';
//    public const ADMIN = 'admin/dashboard';

    public static function redirectTo($guard){
        return $guard.'/dashboard';
    }

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));


        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

i edit it to return public static function redirectTo($guard){ return $guard.'admin.dashboard'; } i now any user can access dashboard even normal user who not have user_type ??

furqanDev's avatar

Check what is the type of other users in the database

Desssha's avatar

@furqanDev i was forgot delete guard and after i delete i face this problem InvalidArgumentException Auth guard [admin] is not defined. no i not have any guard in auth

furqanDev's avatar

@Desssha Just create a new middleware 'Manager',

In Kernel.php

'is_manager' => \App\Http\Middleware\Manager::class,

In Middleware

class Manager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user()->user_type != 1) {
            abort(403);
        }
        return $next($request);
    }
}

In your route Group,

Route::group(['middleware' => 'auth', 'is_manager'], function () {
Route::get('admin/dashboard', function () {
    return view('admin.index');
})->name('admin.dashboard');
Desssha's avatar

@furqanDev problem no not in middleware like i see i delete all guard i was create , but when try access admin dashboard get this error InvalidArgumentException Auth guard [admin] is not defined.

i think this in RedirectIfAuthenticated and RouteServiceProvider

furqanDev's avatar

@Desssha You can change your redirectIfAuthenticated middleware as follow. You can change the condition as you wish.

public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                return $request->user()->user_type != 1 ?
                    redirect()->intended(RouteServiceProvider::MANAGERHOME) :
                    redirect()->intended(RouteServiceProvider::HOME);
            }
        }

        return $next($request);
    }
1 like
Desssha's avatar

@furqanDev what about RouteServiceProvider ? now normal user also access admin dashboard !

furqanDev's avatar

@Desssha Just change the condition,

foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
				if($request->user()->user_type == 1){
					return redirect()->intended(RouteServiceProvider::MANAGERHOME) :
				}else[
					return redirect()->intended(RouteServiceProvider::HOME);
				}
            }
        }
Desssha's avatar

@furqanDev inside this

 public static function redirectTo($guard){
        return $guard.'/dashboard';
    }

``` ?
furqanDev's avatar

@Desssha No, just add this in your routeServiceProvider file. You can change the path like you want.

public const MANAGERHOME = '/admin/dashboard';

public const HOME = '/user/dashboard';
Desssha's avatar

@furqanDev man i do this step . but i not want use guard anymore , because it i use middleware , now middleware not protect route and all users access dashboard . i have only one table for all user and user_type not need guard this way solve error guard admin but not protect route . hope you understand me and thanks for your time

furqanDev's avatar

@Desssha I don't understand you. Where are you getting the problem. While logging in ?

Desssha's avatar

@furqanDev InvalidArgumentException Auth guard [admin] is not defined.

when i try access admin dashboard, i was have guard but delete it and use default from laravel , when try access admin dashboard get this error now

furqanDev's avatar

@Desssha Check the blade file or in controller. You are accessing auth while specifying the guard. Check if there is such thing in the dashboard or in controller which is returning the dashboard view.

auth()->guard('admin')->user() 

or

Auth::guard('admin')->user();
furqanDev's avatar

@desssha Also check in the layouts file as well as header blade files. You need to remove the guard and replace it with just a simple auth()->user()

1 like
jlrdw's avatar

I suggest setup Auth as it was "out of box", then troubleshoot from there as you modify things, using network tab checking request and response.

Please or to participate in this conversation.