Search code examples
laraveleloquenthas-one

laravel hasone not able to get the result


i'm trying to get the role of a user either is it admin or client with hasOne relationship but when i'm trying to get the details and doing dd im getting the exists as false can anyone help me out please

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();
    });
}

//migration for role

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());
 }

Solution

  • You have to access the relationship as a property, not as a method:

    Auth::user()->getrole;