DEV Community 👩‍💻👨‍💻

Cover image for Laravel 9 - Avoid data leakage when using orWhere on a relationship
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on

Laravel 9 - Avoid data leakage when using orWhere on a relationship

Not Bad:
This returns ALL posts where votes are greater than or equal to 100 are returned.

$user->posts()->where('active', 1)->orWhere('votes', '>=', 100)->get();
Enter fullscreen mode Exit fullscreen mode

Good:
This returns Users posts where votes are greater than or equal to 100 are returned.

use Illuminate\Database\Eloquent\Builder;

$users->posts()->where(function (Builder $query) {
     return $query->where('active', 1)->orWhere('votes', '>=', 100);
})->get();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.