New `whereBelongsTo()` Eloquent query builder method

Laravel 8.63.0 ships with a new whereBelongsTo() Eloquent query builder method. Smiling face with heart-shaped eyes

This allows you to remove BelongsTo foreign key names from your queries, and use the relationship method as a single source of truth instead!

1// From:
2$query->where('author_id', $author->id)
3 
4// To:
5$query->whereBelongsTo($author)
6 
7// Easily add more advanced filtering:
8Post::query()
9 ->whereBelongsTo($author)
10 ->whereBelongsTo($cateogry)
11 ->whereBelongsTo($section)
12 ->get();
13 
14// Specify a custom relationship:
15$query->whereBelongsTo($author, 'author')

Tip given by @danjharrin

Like our articles?

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