LogoNavigate back to the homepage

How to migrate ‘with’ and ‘whereHas’ in Laravel?

Yish
October 15th, 2020 · 1 min read

It needs to think about this, for my situation, I need to query when audits table has any data, but the result requiring with it, so how to do this?

Here is my base query, it’s pretty basic, also I need search by specific term.

1$histories = Product::when($no, function($query, $id) {
2 return $query->where('id', 'like', "%{$id}%");
3})->whereHas('audits', function ($query) use ($email) {
4 $query->whereIn('url', ['orders', 'products'])
5 ->latest('audits.id')
6 ->when($email, function($query, $email) {
7 return $query->join('users', 'users.id', '=', 'audits.user_id')->where('email', 'like', "%{$email}%");
8 });
9})

Next, append with conditions, also to know it, you need to tell with function condition( here is the key).

1->with(['audits' => function($query) {
2 $query->whereIn('url', ['orders', 'products']);
3}])
4->paginate((int)$request->get('per_page', 10));

It’s great! Also you can add macroable to AppServiceProvider.

1Builder::macro('withHas', function($relation, $constraint) {
2 return $this->whereHas($relation, $constraint)->with([$relation => $constraint]);
3});

And then you can also do for this

1Product::withHas('audits', function() { ... });

php – Merge ‘with’ and ‘whereHas’ in Laravel 5 – Stack Overflow

More articles from Yish

PHPStorm IDE settings in 2020

PHPStorm settings.

October 15th, 2020 · 1 min read

How do I work in the end of 2020?

一年很快的要結束了,綜觀今年因為疫情嚴重很多事情變得很不方便,但也是做了一些想要達成的目標,關於目標我會在下一篇文來回顧。

October 14th, 2020 · 1 min read
© 2019–2020 Yish
Link to $https://twitter.com/yishlaiLink to $https://github.com/Mombuyish