Using Model Relationship in a Single Query

Using Model Relationship in a Single Query

Consider the following:

Consider the following:

$posts = $this->model->newQuery()
    ->whereIn('user_id', $user->following) // specifically this line
    ->orWhere('user_id', $user->id)

The problem with the above is that there are two queries:

  • Get following: $user->following
  • Get posts: Above

This would be much more efficient with the use of a subquery, however, I cannot actually remember the correct way to do it...

I have tried all of the following:

// This was a long-shot...
...->whereIn('user_id', function ($query) use ($user) {

// This works but pretty sure it can be done better with eloquent... ...->whereIn('user_id', function ($query) use ($user) { $query->select('follow_id') ->from('user_follows') ->where('user_id', $user->id); });

Is there a way that this can be achieved by using the previously defined relationship $user->following() instead of manually defining the relationship query like the last example above?


The following relationship is defined as follows:


  • Get the users that the user follows.
  • / public function following() { return $this->belongsToMany('SomeApp\User\Models\User', 'user_follows', 'user_id', 'follow_id')

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

In Laravel 6 tutorial, we learn how to use PHP artisan command interface (CLI) to clear the cache from Laravel 6.8 application. How To Clear Cache in Laravel 6.8 Application using Artisan Command Line Interface (CLI)? How to clear route cache using php artisan command? How to easily clear cache in Laravel application? How to clear config cache in PHP Laravel via artisan command? How to clear Laravel view cache? How to Reoptimized class in Laravel via artisan CLI?

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather. Laravel Weather is a good package which we can use to get weather data. It's a wrapper around Open Weather Map API (Current weather). A wrapper around Open Weather Map API (Current weather)

Laravel Sweet Alert | How to use the SweetAlert package in Laravel PHP

Sweet Alert is a laravel wrapper around #sweetalert javascript library for showing alert or notification message. This is a great package created by rashid, and this laravel package is very famous because it has tonnes of features you can choose from.