我试图获得用户的角色,无论是管理员还是具有hasOne关系的客户端,但是当我试图获取详细信息并且正在尝试获取存在为false时,任何人都可以帮助我请出来
this is the result when im using dd in controller
//migration for user
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
//迁移角色
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->enum('role',['Club Manager','Admin','Mc']);
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
//的usermodel
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use \App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function Role(){
return null;
}
public function getrole(){
$role=$this->hasMany('App\Role');
return $role;
}
public function getuserRole(){
return Role::where('user_id',$this->id)->first();
}
}
//Controller
public function getrole(){
dd(Auth::user()->getrole());
}
答案 0 :(得分:2)
您必须将该关系作为属性访问,而不是作为方法:
Auth::user()->getrole;