您可以创建自己的中间件,而不是使用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
。
这是一个抽象的想法,但你现在可以实现你自己的一个,所以check the documentation欲了解更多信息。
此“已批准”列出现在哪个表中?用户表或其他表? – Bogdan
新闻条目的另一个表,控制器被称为NewsControlller – KinsDotNet