I have a Middleware for ajax-only routes.
// AjaxOnly Middleware class
public function handle($request, Closure $next)
{
if (!$request->ajax()) {
// dd('I\'m (condition) working as expected!');
return response()->view('layouts.app');
}
dd('I never work!');
return $next($request);
}
Here is my routes web.php
// Ajax only routes
Route::group(['middleware' => 'ajaxOnly'], function () {
// Work an print 'false'
// dd(Request::ajax());
// Redirect me to /login page
Route::group(['middleware' => ['auth:user']], function () {
Route::get('/', 'HomeController@index')->name('home');
});
// Authentication routes
Auth::routes();
});
So, can someone explain why the code continues to run inside Middleware-protected closure? Thanks.
UPD: Just clarify -
You can adjust your middleware priority to ensure the correct middleware executes in the correct order. You can achieve this by overriding the default $middlewarePriority
in your Kernel.php
file.
/**
* The priority-sorted list of middleware.
*
* Forces the listed middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\xxx\Middleware\AjaxOnly::class,
\Illuminate\xxx\Middleware\Auth::class,
];
You can follow what Illuminate\Routing\Router
does with $middlewarePriorty
here in the source code.