我从这里使用Entrust 中间件。一切都很好,除非我想在登录时向管理员公开某个页面 以及向任何未登录的用户公开。
在此处的帮助下,我添加了以下中间件,但是当我点击 url 时,它说重定向太多。
namespace App\Http\Middleware;
use App\Models\User;
use App\Models\Role;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Database\Eloquent\Collection;
class CheckPermission {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct( Guard $auth )
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle( $request, Closure $next )
{
if ( $this->auth->guest() )
{
$user = new User;
$user->id = 0;
$user->username = 'Guest';
$role = Role::find(9);// EXPLANATION OF 9 IS GIVEN BELOW UNDER CODE
$user->roles = new Collection;
$user->roles->add( $role );
}
else
{
$user = $this->auth->user();
}
// Automatically check permission based on route name
/*
if ( !$user->can( $request->route()->getName() ) )
{
// Handle denied permission, e.g. abort(401)
}
*/
return $next( $request );
}
}
数据库更改:在roles
表中我添加了一行 id 9 和 name guest
。如何在 Entrust 中添加访客支持,以便任何未登录的用户都将被视为访客,并允许他访问某些路线。