Skip to content

[9.x] Added Eloquent withWhereHas method#42597

Merged
taylorotwell merged 4 commits into
laravel:9.xfrom
eusonlito:feature/eloquent-withWhereHas
Jun 1, 2022
Merged

[9.x] Added Eloquent withWhereHas method#42597
taylorotwell merged 4 commits into
laravel:9.xfrom
eusonlito:feature/eloquent-withWhereHas

Conversation

@eusonlito
Copy link
Copy Markdown
Contributor

@eusonlito eusonlito commented May 31, 2022

There are a lot of times that we need to load a relationship using with with the same conditions that we use for whereHas.

This method simplifies this selection by avoiding repeating the code used both to filter with whereHas and then to select that same record using with. There is less code, it is more readable and easier to maintain.

Before

CollectionModel::whereHas('products', function ($query) {
    $query->where('enabled', true)->where('sale', true);
})->with(['products' => function ($query) {
    $query->where('enabled', true)->where('sale', true);
});

After

CollectionModel::withWhereHas('products', fn ($query) => $query->where('enabled', true)->where('sale', true));

If it's ok for you, I will add tests :)

@taylorotwell
Copy link
Copy Markdown
Member

I think it seems pretty decent if you want to add tests. Mark as ready for review when done.

@taylorotwell taylorotwell marked this pull request as draft May 31, 2022 21:34
@eusonlito eusonlito marked this pull request as ready for review June 1, 2022 07:31
@taylorotwell taylorotwell merged commit 702c119 into laravel:9.x Jun 1, 2022
@eusonlito eusonlito deleted the feature/eloquent-withWhereHas branch June 1, 2022 14:10
@lovemintblue
Copy link
Copy Markdown

nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants