0
votes

I would like to display privileges('name') instead of idPrivilege in the user collection. I have tried to add a relationship and use it in an Eloquent call but I'm getting an error.

User model

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';

    protected $primaryKey = 'idUser';

    protected $fillable = [
        'name', 'email',
    ];

    protected $hidden = [
        'password', 'updated_at',
    ];

    public function privilege()
    {
        return $this->hasOne(Privilege::class, 'idPrivilege', 'idPrivilege');
    }
}

Privilege model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Privilege extends Model
{
    protected $table = 'privileges';

    protected $primaryKey = 'idPrivilege';

    protected $fillable = [
        'name',
    ];

    protected $hidden = [
        'updated_at', 
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'idPrivilege', 'idPrivilege');
    }
}

UserController

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
    public function relationTest()
    {
        return User::where('idUser', 1)->privilege()->get();
    }
}

I'm getting the below error when I use with('privilege') to my User collection is added privilege collection.

Call to undefined method Illuminate\Database\Eloquent\Builder::privilege().

2
Please can you show what you're expected output is?Rwd
in answer below i show the output i expectMartin

2 Answers

0
votes

where returns a Builder instance on which a privilege method does not exist, so you can simply use it as such:

return User::find(1)->privilege()->get();;

-- EDIT

User::find(1)->with(['privilege' => function($query) { 
   $query->select('name');
}])->get();

0
votes

I can achieve it by using resource:

$user = User::where('idUser', 1)->with('privilege')->first();
return UserResource::make($user);

Inside UserResource:

public function toArray($request)
{
    return [
        'idUser' => $this->idUser,
        'name' => $this->name,
        'email' => $this->email,
        'privilege' => $this->privilege['name'],
        'createdAt' => $this->created_at,
    ];
}

but was hoping there is simplier method of getting that.

output:

{
"data": {
"idUser": 1,
"name": "Martin",
"email": "[email protected]",
"privilege": "user",
"createdAt": "2019-05-05T01:11:43.000000Z"
}
}