DEV Community

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

Posted on

3 1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay