Simplifying 'Belongs To' Relationship Queries

• 35 sec read • Share

A useful addition to the Laravel framework was added recently, which allows for a cleaner syntax when retrieving items via a 'belongsTo' relationship.

Previously if you wanted to retrieve posts for a specific user you would build out a where clause as follows:

1use App\Models\Post;
3$posts = Post::where('user_id', $user->id)->get();

A newer and cleaner syntax allows you to do the following:

1$posts = Post::whereBelongsTo($user)->get();

You may also manually specify which relationship to query by providing the name of the relationship as the second argument:

1$posts = Post::whereBelongsTo($user, 'author')->get();

I'm always a huge fan of changes like these that improve code readability.

Join my mailing list.

Receive my latest content by email. No spam, ever.