Skip to content

Commit

Permalink
Add new validateWithBag macro to Request (#30896)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhenri-l authored and taylorotwell committed Dec 23, 2019
1 parent 6b8a94e commit fdeb204
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Illuminate/Foundation/Providers/FoundationServiceProvider.php
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Http\Request;
use Illuminate\Support\AggregateServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\ValidationException;

class FoundationServiceProvider extends AggregateServiceProvider
{
Expand Down Expand Up @@ -54,6 +55,16 @@ public function registerRequestValidation()
Request::macro('validate', function (array $rules, ...$params) {
return validator()->validate($this->all(), $rules, ...$params);
});

Request::macro('validateWithBag', function (string $errorBag, array $rules, ...$params) {
try {
return $this->validate($rules, ...$params);
} catch (ValidationException $e) {
$e->errorBag = $errorBag;

throw $e;
}
});
}

/**
Expand Down
20 changes: 20 additions & 0 deletions tests/Integration/Validation/RequestValidationTest.php
Expand Up @@ -28,4 +28,24 @@ public function testValidateMacroWhenItFails()

$request->validate(['name' => 'string']);
}

public function testValidateWithBagMacro()
{
$request = Request::create('/', 'GET', ['name' => 'Taylor']);

$validated = $request->validateWithBag('some_bag', ['name' => 'string']);

$this->assertSame(['name' => 'Taylor'], $validated);
}

public function testValidateWithBagMacroWhenItFails()
{
$request = Request::create('/', 'GET', ['name' => null]);

try {
$request->validateWithBag('some_bag', ['name' => 'string']);
} catch (ValidationException $validationException) {
$this->assertEquals('some_bag', $validationException->errorBag);
}
}
}

0 comments on commit fdeb204

Please sign in to comment.