Repeatable Callback Functions

If you have a callback function that you need to re-use multiple times, you can assign it to a variable, and then re-use.

1$userCondition = function ($query) {
2 $query->where('user_id', auth()->id());
3};
4 
5// Get articles that have comments from this user
6// And return only those comments from this user
7$articles = Article::with(['comments' => $userCondition])
8 ->whereHas('comments', $userCondition)
9 ->get();

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