Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Added Eloquent withWhereHas method #42597

Merged
merged 4 commits into from
Jun 1, 2022
Merged

[9.x] Added Eloquent withWhereHas method #42597

merged 4 commits into from
Jun 1, 2022

Conversation

eusonlito
Copy link
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
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

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