In User Model :
public function role(){
return $this->hasOne('App\Model\Roles','id','role_id');
}
In Roles Model:
public function user(){
return $this->belongTo('App\Model\Users');
}
In method :
$query = Users::where('id', $id)->get();
What i get (in JSON):
[{"id":2,"user_name":"hazardgeek","user_email":"nwasuper@example.com","user_phone":"*******","user_password":"*********","remember_token":"*****","role_id":2}]
What i actually want:
i want the role_title
column from the Roles model, not role_id
from Users table. Like this, ......user_password":"thesupernwa","remember_token":null,"role_title":"customer"}]
How can i achieve this?? Thank you.
In User.php Model
public function User(){
protected $appends = ['role_title'];
public function getRoleTitleAttribute(){
$role = $this->getRelation('role');
return !empty($role) ? $this->role->role_title : null;
}
}
I ended up using a raw queries to retrieve the right response
return DB::table('ctr_user')
->select('ctr_user.id AS user_id','user_name','user_email','user_phone','user_password','remember_token','ctr_role.role_title AS title')
->rightJoin('ctr_role', 'ctr_role.id','=','ctr_user.role_id')
->where('ctr_user.id','=',$id)
->get();
response return by this raw queries is exactly response I need using Eloquent.
But still how?