我需要指定对用户进行身份验证的重定向使用。我在默认的laravel用户表中添加一列:“ is_admin”,其值为“ 1”和“ 0”
在我的控制器中,我尝试过:
if(Auth::user()->is_admin=1){
return view('index');
}
else {
return view('auth.login');
};
但是,即使认证具有is_admin = 0,
我该如何解决这个问题?有没有更好的方法来执行此条件?谢谢
答案 0 :(得分:2)
您的问题是,您在if
语句中分配了一个值,只有一个=
会分配一个值,而不是两个==
(或三倍) ===
)来比较值。
只有一个=
时发生的事情是,您将1
的值赋给=
之前的任何值,这将得出“真实”的值值,表示if
始终为真,而无论else
永远不会执行。
您应该将其更改为此:
if (Auth::user()->is_admin == 1){ // Notice the two == here
return view('index');
} else {
return view('auth.login');
}
请注意,我已在最后删除了分号。
答案 1 :(得分:1)
To avoid this kind of issue you kind manage the way you specify value by creating const
in you User
Model. this allow you to have the same values which have same type all the time
class User extends Model
{
const ADMIN_USER = "1";
const REGULAR_USER = "0";
public function is_admin()
{
return $this->attributes['is_admin'] == self::ADMIN_USER;
}
}
when creating a non admin user you use this
User::create([
// SET OTHER ATTRIBUTE
'is_admin' => User::REGULAR_USER
]);
when creating the admin user you use this
User::create([
// SET OTHER ATTRIBUTE
'is_admin' => User::ADMIN_USER
]);
And when it come to check it in your view, you will have just to call the is_admin
method on the Auth::user()->is_admin()
if(Auth::user()->is_admin()){
// Your code goes here
} else {
// And other codes goes here
}