Search code examples
sqllaraveleloquentlaravel-5.8laravel-query-builder

How to get following users posts in Laravel 5.8


I have two models in my Laravel 5.8 project, relationships is shown below in both model classes. How can I get every single post records related with every single user that I follow using just a single sql query ? Can I get it using Eloquent Query Builder or I need a Raw SQL Query ? Can Someone show me the SQL query to do it ?

Sorry, I didn't know what title to put in the question.

Thanks in advance !

User Class.

class User extends Authenticatable implements MustVerifyEmail{

   use Notifiable, MessageAccessible, TagsCreator;

   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
      'name',
      "lastname",
      "country",
      "city",
      "phone_number",
      'e_mail',
      'password',
      "role_id",
      "profile_picture",
      "occupation",
      "biography"
   ];

   /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
   protected $hidden = [
      'password',
      'remember_token'
   ];

   /**
    * The attributes that should be cast to native types.
    *
    * @var array
    */
   protected $casts = ['email_verified_at' => 'datetime'];

   public function posts(){
      return $this->hasMany(Post::class);
   }

   public function followers(){
      return $this->belongsToMany(User::class, 'follower_followed', 'followed_id', 'follower_id');
   }

   public function following(){
      return $this->belongsToMany(User::class, 'follower_followed', 'follower_id', 'followed_id');
   }
}

Post Class.

class Post extends Model{

   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
      'user_id',
      "post_permission_id",
      "title",
      "content",
      "likes",
      "dislikes"
   ];

   public function user(){
      return $this->belongsTo(User::class);
   }
}

Solution

  • I think what you need to do is this.

    Not sure but in some Laravel versions you have to use select instead of pluck here. This defo works in 5.6

    $posts = Post::whereIn('user_id', User::find($user_id)->followers->pluck('id'))->get();
    

    then you might wanna order the posts by follower

    $posts = Post::whereIn('user_id', User::find($user_id)->followers->pluck('id'))->orderBy('user_id', 'ASC')->get();
    

    Here is the Documentation for whereIn Scroll a bit down, there is no direct anchor on whereIn :-)