我有一个使用 Laravel 5 开箱即用身份验证的应用程序。仅当名为“approved”的字段等于 1 时,我才需要对 Controller 的 show 方法进行身份验证。
如何有条件地要求使用中间件进行身份验证,以便未经身份验证的用户可以访问批准列等于 1 的条目,但只有经过身份验证的用户才能看到批准列等于 0 的条目。
我的构造函数当前如下所示:
public function __construct(){
$this->middleware('auth', ['only' => ['edit', 'destroy', 'approve', 'markRecovered']]);
}
最佳答案
您可以创建自己的中间件而不是使用 Laravel
默认auth
中间件,在这种情况下,您可以使用如下内容创建一个中间件,例如“checkApproval”:
php artisan make:middleware checkApproval
然后在你的app/Http/Middleware
中您将在目录中找到创建的新中间件,它将包含基本结构,包括 handle
方法,所以现在您可以在该中间件的 handle
中编写代码检查user
的方法的状态和approved
字段,然后重定向到 login
如果条件不匹配或不允许访问,则返回页面。这是一个基本想法:
use Illuminate\Contracts\Auth\Guard;
class CheckPermission implements Middleware {
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function handle($request, Closure $next)
{
if($this->auth->guest() && !$this->checkApproval($request))
{
return redirect('login');
}
return $next($request);
}
protected function checkApproval($request)
{
// Get the auth/logged in user
// $user = $request->user();
// Get a parameter from route
// $id = $request->route()->parameter('id')
// Check the approved field here and return true or false
}
}
现在在 app/Http/Kernel.php
中为中间件分配一个快捷键文件。默认情况下,$routeMiddleware
此类的属性包含 Laravel
中包含的中间件的条目。 。要添加您自己的,只需将其附加到此列表并为其分配 key
在您的 route/controller
中使用,例如 checkApproval
所以代替auth
您可以使用checkApproval
对于该方法view
在你的 Controller 中。
这是一个抽象的想法,但您现在可以实现自己的想法,所以 check the documentation了解更多信息。
关于php - 如何在 Laravel 5 中有条件地要求身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30672303/