Skip to content

Commit ff197bf

Browse files
[9.x] Add handling of object being passed into old method (#41842)
* Add handling of model being passed into old method * decouple database concern with the http concern * check if object, and add test to cover an array being passed through * lint * check if instance of model instead of object with a getAttribute method * Update InteractsWithFlashData.php * Update InteractsWithFlashData.php Co-authored-by: Taylor Otwell <[email protected]>
1 parent 2f51de5 commit ff197bf

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/Illuminate/Http/Concerns/InteractsWithFlashData.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,21 @@
22

33
namespace Illuminate\Http\Concerns;
44

5+
use Illuminate\Database\Eloquent\Model;
6+
57
trait InteractsWithFlashData
68
{
79
/**
810
* Retrieve an old input item.
911
*
1012
* @param string|null $key
11-
* @param string|array|null $default
13+
* @param \Illuminate\Database\Eloquent\Model|string|array|null $default
1214
* @return string|array|null
1315
*/
1416
public function old($key = null, $default = null)
1517
{
18+
$default = $default instanceof Model ? $default->getAttribute($key) : $default;
19+
1620
return $this->hasSession() ? $this->session()->getOldInput($key, $default) : $default;
1721
}
1822

tests/Http/HttpRequestTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Illuminate\Session\Store;
99
use Illuminate\Support\Carbon;
1010
use Illuminate\Support\Collection;
11+
use Illuminate\Tests\Database\Fixtures\Models\Money\Price;
1112
use InvalidArgumentException;
1213
use Mockery as m;
1314
use PHPUnit\Framework\TestCase;
@@ -950,6 +951,26 @@ public function testOldMethodCallsSession()
950951
$this->assertSame('boom', $request->old('foo', 'bar'));
951952
}
952953

954+
public function testOldMethodCallsSessionWhenDefaultIsArray()
955+
{
956+
$request = Request::create('/');
957+
$session = m::mock(Store::class);
958+
$session->shouldReceive('getOldInput')->once()->with('foo', ['bar'])->andReturn(['bar']);
959+
$request->setLaravelSession($session);
960+
$this->assertSame(['bar'], $request->old('foo', ['bar']));
961+
}
962+
963+
public function testOldMethodCanGetDefaultValueFromModelByKey()
964+
{
965+
$request = Request::create('/');
966+
$model = m::mock(Price::class);
967+
$model->shouldReceive('getAttribute')->once()->with('name')->andReturn('foobar');
968+
$session = m::mock(Store::class);
969+
$session->shouldReceive('getOldInput')->once()->with('name', 'foobar')->andReturn('foobar');
970+
$request->setLaravelSession($session);
971+
$this->assertSame('foobar', $request->old('name', $model));
972+
}
973+
953974
public function testFlushMethodCallsSession()
954975
{
955976
$request = Request::create('/');

0 commit comments

Comments
 (0)