我有Auth
App\Http\Middleware\
在我的内核中,我添加了他:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'Groups' => \App\Http\Middleware\Groups::class,
'Auth' => \App\Http\Middleware\Auth::class,
];
此中间件包含
<?php
namespace App\Http\Middleware;
use Closure;
class Auth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if( !auth()->check() )
{
return abort(404);
}
return $next($request);
}
}
在我的控制器方法中,我使用
$this->middleware('Auth');
但这根本不起作用。
当我拿走'Auth' => \App\Http\Middleware\Auth::class,
并将其放入protected $middlewareGroups
\App\Http\Middleware\Auth::class,
时,它就可以了。但对于每一页。所以当我没有记录时,abort404。
这里有什么问题? 我看不出来,对我来说很好看。
但是这个中间件不适用于我有$this->middleware('Auth');
我没有登录但页面显示为正常。
应该有abort404被解雇因为我没有被记录
是什么让我错了?
答案 0 :(得分:11)
$middlewareGroups
时遇到的问题
开箱即用,自动应用Web中间件组 您的routes / web.php文件由RouteServiceProvider。
如果你想在cotroller中只有一个动作的中间件,你可以将中间件绑定到路由:
Route::get('yourRout', 'YourController@actionX')->middleware('auth');
或者您可以在控制器的构造函数中添加它:
public function __construct()
{
$this->middleware('auth', ['only' => ['edit']]);
}
或者你可以尝试(自Laravel 5.3以来):
public function __construct()
{
$this->middleware('auth')->only(['edit']);
}