[英]Laravel 5.1 Block users using Bican roles
我想知道,我怎么能通過這個包禁止人們......
所以我現在正在使用Laravel 5.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角色)。
現在,我希望能夠使用“禁止”表中的數據向我的被禁用用戶顯示自定義禁止視圖。
最好的方法是什么?
如果您添加一個新的中間件並在您的控制器中調用,用戶可以訪問該頁面,它將檢查它們是否被禁止
BannedMiddleware.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);
}
}
和編輯您kernal.php
下protected $routeMiddleware
添加此
'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();
}
這個功能是因為我有另一種方法來存儲禁令等...
app/http/kernel.php
添加到protected $middleware
數組中的app/http/kernel.php
。
\App\Http\Middleware\CheckBanMiddleware::class,
這提供了在每個請求之前檢查數據。
而且你已經完成了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.