Runcible
Runcible

Reputation: 3098

When returning a Laravel model, how do I restrict columns while also using with()?

I have a model User defined as below:

<?php
class User extends Eloquent {

public function roles() {
  return $this->belongsToMany('Role');
}

How do I write a query which will fetch only specific fields from User, along with all fields from each Role?¨ I do not want to use the hidden property on the User model, because in different cases I want different subsets of the fields.

This works, but of course returns all fields from User:

$user = User::with('roles')->findOrFail($id);

This correctly limits the fields of User but returns nothing for the roles - just an empty array

$user = User::with('roles')->select(['name','email'])->findOrFail($id);

Any attempt to reference the roles field inside the select gives an error.

Upvotes: 0

Views: 516

Answers (2)

Sher Afgan
Sher Afgan

Reputation: 1234

You have to do this way in eager loading.

$user = User::with(array('roles' => function($q)
    {
        $q->select('field1');

    }))->select(['name','email'])->findOrFail($id);

Upvotes: 1

Gaurav Dave
Gaurav Dave

Reputation: 7474

Try this code:

$with = array('roles' => array('id', 'name'));
$user = User::with($with);

See if that help.

Upvotes: 4

Related Questions