Laravel: How to get selected Base Table columns with Eager Loading?

For example, the structure of the table.

User
-----
-id
-role_id
-fname
-lname
-country_code
-mobile
-password
-remember_token
-email
-address
-location_id

And another table

Role
-----
-id
-name

Now, if I want all the user information from the user table with the role table, I will write like this.

$ user = User :: with ('Role') → where ('users.id', $ id) → first () → toArray ();

But it will retrieve all the data from the user table. I need selected columns of user table with active load. As soon as fname, lname, mobile, email from the user table and role_name from the role table.

I know how to select specific columns of a linked table as shown below.

public function Role(){
    return $this->belongsTo('App\Role')->select('id','name as role_name');
}

But how to select specific columns of a user table using ()?

+4
2

- ( , ):

$user = User::with('Role')
            ->where('users.id',$id)
            ->select('users.fname','users.lname','users.mobile','users.email', 'roles.name as role_name')
            ->first()->toArray();

.

0

, ;

User::with(['Role' => function ($query) {
    $query->select('name');
}])->select('fname', 'lname', 'mobile', 'email', 'role_id')->whereId($id)->first()->toArray();
0

All Articles