我對Laravel非常陌生,並且正在嘗試爲用戶實現角色。Laravel 5檢查角色給出錯誤「嘗試獲取非對象的屬性」
- 我已經創建與它
- 相關聯的角色表和模型我添加了一個列
role
到users
表。 - 我現在試圖去檢查在
User
模型
編輯角色:一個答案/這裏的解釋後,我在users
表改變role
到role_id
但我仍然得到同樣的錯誤。
這裏是我的用戶模型...
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Auth;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
// more stuff
public function role()
{
return $this->belongsTo('App\Role');
}
public function isAdmin()
{
return $this->role->slug == 'admin';
}
}
而且我的榜樣
<?php namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Role extends Eloquent {
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\User');
}
}
當我去我的管理頁面,我有以下功能...
public function index(User $user)
{
if ($user->isAdmin()) {
return view('admin/home_admin');
}
else {
return redirect('home');
}
}
但是我得到錯誤...
嘗試獲取User.php中非對象的屬性62行 HandleExceptions-> handleError('8','試圖獲取非對象的屬性 ','/ home/vagrant/Code/esearch /應用程序/ user.php的」,‘62’,62
我試圖此而在記錄和不與正確的角色登錄陣列()) 在user.php的線。我在這裏錯過了很明顯的東西嗎
在最後一個面板中更改您的User to Guard。這應該是你正在尋找的修復。或者你可以直接使用'Auth :: user() - > isAdmin()' –
這個工作謝謝 – Adrian