Selecting fields inside eager loading method "with"

Suppose there is a relation Post belongsTo User.

If we are retrieving posts with associated user relation, we can use eager loading method "with" to further limit the fields within this relation. The following snippet can be used for this.

// here inside with() method for relation user we are selecting id, name, email only instead of all the fields of users tbl
$posts = Post::select('title', 'user_id')->with('user:id,name,email')->get();


In the example above, id, name and email fields are selected only within users table which is indicated by ":" operator next to the relation name "user" inside eager loading method "with".

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent