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

[7.x] Add existsOr and doesntExistOr to the query builder #30479

Closed
wants to merge 3 commits into from
Closed

[7.x] Add existsOr and doesntExistOr to the query builder #30479

wants to merge 3 commits into from

Conversation

SjorsO
Copy link
Contributor

@SjorsO SjorsO commented Oct 31, 2019

In my controllers, I often use something like this to validate requests:

$hasOpenDossier = $user->dossiers()
    ->whereNull('closed_at')
    ->exists();

if ($hasOpenDossier) {
    abort(422, 'User already has an open dossier');
}

With this PR, I can do this instead:

$user->dossiers()
    ->whereNull('closed_at')
    ->doesntExistOr(function () {
        abort(422, 'User already has an open dossier');
    });

This way I don't have to create a temporary variable, and the code is more logically grouped together (which is especially nice in more complex projects where you can have three of these checks in a row).

I would almost always use this feature for aborting. It could also be used for other things, but to be honest I can't really think of any. (maybe adding a doesntExistOrAbort macro to my projects would be a better solution).


An alternative to adding two new methods is adding an optional $callback argument to the exists() and doesntExist() methods. I think adding two new methods is a cleaner way of doing it, mainly because it keeps the parameters and return type of exists() and doesntExist() simple.

@taylorotwell
Copy link
Member

You can send this to 6.x branch since it is not breaking. Thanks.

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.

2 participants