`whereHas()` multiple connections

1// User Model
2class User extends Model
3{
4 protected $connection = 'conn_1';
5 
6 public function posts()
7 {
8 return $this->hasMany(Post::class);
9 }
10}
11 
12// Post Model
13class Post extends Model
14{
15 protected $connection = 'conn_2';
16 
17 public function user()
18 {
19 return $this->belongsTo(User::class, 'user_id');
20 }
21}
22 
23// wherehas()
24$posts = Post::whereHas('user', function ($query) use ($request) {
25 $query->from('db_name_conn_1.users')->where(...);
26 })->get();

Tip given by @adityaricki

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