结合Middleware实现后台管理
打赏作者

msndmy

发现一个小问题,不知道这个是不是Laravel的bug
我把Auth::loginUsingId(1);可以正常访问
修改成Auth::loginUsingId(3);应该是直接不能访问了,但是刷新第一次还是可以访问,再次刷新才不能访问,是不是因为之前用户登录的信息没有删掉?

msndmy

但是将Auth::loginUsingId(3);这句话放到__construct函数里,middleware之前就没有这个bug

daimingkang

我建议登录 Auth::loginUsingId(2); 这个代码放到其他控制器 应为 middleware 首先访问 所以执行不到登录 所以不管谁都会跳转到首页

jihaichuan 回复 daimingkang

我跟着视频做的,发现Auth::loginUsingsId(1) 必须放到 middleaware 前面

hard88

登陆应该在中间层验证之前把。。 看了好久才找到这个错误。

jihaichuan 回复 hard88

赞同, 我也是

Gavin1024

也是啊 应该改为后置中间件 这样就能先登录后验证了

jihaichuan

想问一下 在User.php 模型中 有一个 hasRole方法,方法中的 $this->roles 是怎么来的 , 求解

JellyBool 回复 jihaichuan

roles() 这个方法就是的

jihaichuan 回复 JellyBool

嗯嗯,谢谢, 知道了

asion

@JellyBool Auth::loginUsingId(1)登录操作是要放在middleware之前的吗?因为我第一次访问时dd($request->user())是null
,如果要放在middleware之前,要怎么实现比较好呢

JellyBool 回复 asion

你就写在 routes 文件的顶部就好了

laravelcasts

request->user()->isAdmin()返回true ,在Controller中调用user->isAdmin()返回false 不知道为什么

JellyBool 回复 laravelcasts

这个你确保判断条件是一致的么?同一个用户?

laravelcasts 回复 JellyBool

是啊,在web.php中写的Auth::loginUsingId

JellyBool 回复 laravelcasts
user->isAdmin()

这里的 user 是哪里来的

laravelcasts 回复 JellyBool

use App\User;
public function __construct(User $user)
{
$this->user = $user;
$this->middleware(‘admin’);
}

JellyBool 回复 laravelcasts

这个 user 又不是登录进来的 user

laravelcasts 回复 JellyBool

’ Gate::define($auth->name,function (User user)use(user) use (auth) {
return user>hasRole(user->hasRole(auth->roles);
});'
这里依赖注入的user也是laravel自己实例化的,为什么是登录的用户呢?

JellyBool 回复 laravelcasts

这个代码是?错了么?

laravelcasts 回复 JellyBool

没错,只是和在controller中依赖注入的user相比这里的可以获取到当前登录的用户,就很不解 ··· Gate::define(auth->name,function (User user)use(user) use (auth) {
return user>hasRole(user->hasRole(auth->roles);
});
···