Skip to content

Commit 0ef435a

Browse files
mathieututaylorotwell
authored andcommitted
[5.4] Check if Collection is empty and prevent exception on fresh method. (#19671)
* Add fresh method on Eloquent/Collection. * Rewrite completely the method to avoid multiple database calls. Add full tests for Model::fresh() and Collection::fresh() methods. * Update tests for php5.6 and Carbon v1.20.0 * Check if collection is empty and prevent exception. * styleCI
1 parent 05060b1 commit 0ef435a

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

src/Illuminate/Database/Eloquent/Collection.php

+4
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,10 @@ public function map(callable $callback)
146146
*/
147147
public function fresh($with = [])
148148
{
149+
if ($this->isEmpty()) {
150+
return new static;
151+
}
152+
149153
$model = $this->first();
150154

151155
$freshModels = $model->newQueryWithoutScopes()

tests/Database/DatabaseEloquentCollectionTest.php

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ public function testQueueableCollectionImplementationThrowsExceptionOnMultipleMo
357357
$c = new Collection([new TestEloquentCollectionModel, (object) ['id' => 'something']]);
358358
$c->getQueueableClass();
359359
}
360+
361+
public function testEmptyCollectionStayEmptyOnFresh()
362+
{
363+
$c = new Collection();
364+
$this->assertEquals($c, $c->fresh());
365+
}
360366
}
361367

362368
class TestEloquentCollectionModel extends \Illuminate\Database\Eloquent\Model

0 commit comments

Comments
 (0)