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

[11.x] Add Conditionable Trait to Request #53775

Merged
merged 2 commits into from
Dec 6, 2024
Merged

Conversation

ahmeti
Copy link
Contributor

@ahmeti ahmeti commented Dec 6, 2024

Just like in the Query Builder class, we can use the when method in the Request class.

/**
 * Prepare the data for validation.
 */
protected function prepareForValidation(): void
{
    $this->when($this->input('account_id'),
        fn (Request $req, int $accountId) => $req->merge(['account_name' => Account::getName($accountId)]),
        fn (Request $req) => $req->merge(['account_name' => null])

    )->when($this->input('contact_id'),
        fn (Request $req, int $contactId) => $req->merge(['contact_name' => Contact::getName($contactId)]),
        fn (Request $req) => $req->merge(['contact_name' => null])
    );
}

/**
* Apply the callback if the given "value" is (or resolves to) truthy.
*
* @template TWhenParameter
* @template TWhenReturnType
*
* @param (\Closure($this): TWhenParameter)|TWhenParameter|null $value
* @param (callable($this, TWhenParameter): TWhenReturnType)|null $callback
* @param (callable($this, TWhenParameter): TWhenReturnType)|null $default
* @return $this|TWhenReturnType
*/
public function when($value = null, ?callable $callback = null, ?callable $default = null)
{
$value = $value instanceof Closure ? $value($this) : $value;
if (func_num_args() === 0) {
return new HigherOrderWhenProxy($this);
}
if (func_num_args() === 1) {
return (new HigherOrderWhenProxy($this))->condition($value);
}
if ($value) {
return $callback($this, $value) ?? $this;
} elseif ($default) {
return $default($this, $value) ?? $this;
}
return $this;
}

@rodrigopedra
Copy link
Contributor

rodrigopedra commented Dec 6, 2024

Why not add the Illuminate\Support\Traits\Conditionable trait?

@ahmeti
Copy link
Contributor Author

ahmeti commented Dec 6, 2024

Why not add the Illuminate\Support\Traits\Conditionable trait?

Thank you @rodrigopedra, good catch! Updated.

@ahmeti ahmeti changed the title [11.x] Add when() to Request [11.x] Add Conditionable Trait to Request Dec 6, 2024
@taylorotwell taylorotwell merged commit 46f0e57 into laravel:11.x Dec 6, 2024
38 checks passed
browner12 pushed a commit to browner12/framework that referenced this pull request Dec 10, 2024
* [11.x] Add when() to Request

* [11.x] Add when() to Request
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