Laravel HasMany: Load Only Specific Fields But Don't Skip xxxxx_id

Laravel 2-in-1 quick tip about hasMany relationships.

Let's imagine that you have this Model method:

app/Models/City.php:

class City extends Model {
public function restaurants()
{
return $this->hasMany(Restaurant::class);
}
}

Then you may load cities with all their restaurants, like this:

City::with('restaurants')->get();

But what if you don't want to load ALL the fields of the restaurant, to save some memory and bandwidth? You can do this:

City::with('restaurants:id,city_id,name')->get();

But be careful. If you skip the RELATIONSHIP column, it will not give you the data at all:

City::with('restaurants:id,name')->get();

This will return NO restaurants.

avatar

The last 2 queries are the same, probably a mistake ? anyways, thanks for this great site :)

👍 1
avatar

Thanks, well noticed! Fixed now, was writing this thing in a rush, just wanted to save my tweet in a blog format so it would be searchable in the future :)

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials