Skip to content

Commit

Permalink
Allow request input to be retrieved as a collection (laravel#38832)
Browse files Browse the repository at this point in the history
* Allow request input to be retrieved as a collection

* Fix docblock spacing -- styleci

* Remove default input value when collecting key
  • Loading branch information
erikgall authored and victorvilella committed Oct 12, 2021
1 parent 7d954a1 commit 33e4655
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Illuminate/Http/Concerns/InteractsWithInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,17 @@ public function boolean($key = null, $default = false)
return filter_var($this->input($key, $default), FILTER_VALIDATE_BOOLEAN);
}

/**
* Retrieve input from the request as a collection.
*
* @param string|null $key
* @return \Illuminate\Support\Collection
*/
public function collect($key = null)
{
return collect($this->input($key));
}

/**
* Get a subset containing the provided keys with values from the input data.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Http/HttpRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Route;
use Illuminate\Session\Store;
use Illuminate\Support\Collection;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use RuntimeException;
Expand Down Expand Up @@ -502,6 +503,26 @@ public function testBooleanMethod()
$this->assertFalse($request->boolean('some_undefined_key'));
}

public function testCollectMethod()
{
$request = Request::create('/', 'GET', ['users' => [1, 2, 3]]);

$this->assertInstanceOf(Collection::class, $request->collect('users'));
$this->assertTrue($request->collect('developers')->isEmpty());
$this->assertEquals([1, 2, 3], $request->collect('users')->all());
$this->assertEquals(['users' => [1, 2, 3]], $request->collect()->all());

$request = Request::create('/', 'GET', ['text-payload']);
$this->assertEquals(['text-payload'], $request->collect()->all());

$request = Request::create('/', 'GET', ['email' => 'test@example.com']);
$this->assertEquals(['test@example.com'], $request->collect('email')->all());

$request = Request::create('/', 'GET', []);
$this->assertInstanceOf(Collection::class, $request->collect());
$this->assertTrue($request->collect()->isEmpty());
}

public function testArrayAccess()
{
$request = Request::create('/', 'GET', ['name' => null, 'foo' => ['bar' => null, 'baz' => '']]);
Expand Down

0 comments on commit 33e4655

Please sign in to comment.