我想知道,我怎么能通过这个包禁止人们。。。
因此,我目前正在使用Laravel5.1,并试图"禁止"用户访问我的网站。我有一张名为"禁止"的表格,其结构如下:
+---------------+--------------+------------+-------------+------------------+----------------+--+
| TABLE_NAME | COLUMN_NAME | COLUMN_DEFAULT | IS_NULLABLE | DATA_TYPE | CHARACTER_MAXIMUM_LENGTH |
+---------------+--------------+------------+-------------+------------------+----------------+--+
| banned | id | NULL | NO | int | NULL |
| banned | user_id | NULL | NO | int | NULL |
| banned | banned_by | NULL | NO | int | NULL |
| banned | reason | NULL | NO | varchar | 255 |
| banned | expires | NULL | NO | datetime | NULL |
| banned | lifted | NULL | YES | datetime | NULL |
| banned | lifted_by | NULL | YES | int | NULL |
+---------------+--------------+------------+-------------+------------------+----------------+--+
我也有标准的角色结构(bican角色)。
现在,我希望能够用"禁止"表中的数据向我的禁止用户显示自定义的禁止视图。
最好的方法是什么?
如果你添加了一个新的中间件,并在用户可以访问页面的控制器中调用,它将检查他们是否被禁止
禁止的中间件.php
<?php
namespace App'Http'Middleware;
use Closure;
use Illuminate'Support'Facades'Auth;
class BannedMiddleware
{
/**
* Handle an incoming request.
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::guest() && Auth::user()->is('banned')) {
return view('BannedPageView');
}
return $next($request);
}
}
并在protected $routeMiddleware
下编辑您的kernal.php
添加此
'isBanned' => 'App'Http'Middleware'BannedMiddleware::class,
然后在你的控制器中添加这个
public function __construct()
{
$this->middleware('isBanned');
}
这将检查他们是否被禁止,因为他们击中了该控制器中的任何路线。
编辑
为每个请求全局检查所有内容:
制作相同的中间件并放置以下代码:
<?php
namespace App'Http'Middleware;
use Closure;
use Auth;
use App'User;
use DB;
use Carbon'Carbon;
class CheckBanMiddleware
{
/**
* Handle an incoming request.
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::check()) {
if (User::CheckBan()) {
$bandata = DB::table('banned')->where('user_id', '=', Auth::id())->where('lifted', '=', Null)->where('expires', '>=', Carbon::now())->first();
return response()->view('banned', ['bandata' => $bandata]);
}
}
return $next($request);
}
}
在User.php
中,创建一个新函数:
public static function CheckBan()
{
return DB::table('banned')->where('user_id', '=', Auth::id())->where('lifted', '=', Null)->where('expires', '>=', Carbon::now())->exists();
}
这个功能是因为我有另一种方法来存储禁令等…
将以下行添加到protected $middleware
数组中的app/http/kernel.php
。
'App'Http'Middleware'CheckBanMiddleware::class,
这提供了在每次请求之前检查数据。
你完了!