Skip to content

Commit

Permalink
[8.x] Preserve eloquent collection type after calling ->fresh() (#34848)
Browse files Browse the repository at this point in the history
* Preserve eloquent collection class type after calling ->fresh()

* Re-order imports

* Update ->fresh() to filter out non-existant models

* Fix ->fresh() test
  • Loading branch information
calebporzio committed Oct 16, 2020
1 parent 3e4f5f4 commit 914a203
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
8 changes: 5 additions & 3 deletions src/Illuminate/Database/Eloquent/Collection.php
Expand Up @@ -300,9 +300,11 @@ public function fresh($with = [])
->get()
->getDictionary();

return $this->map(function ($model) use ($freshModels) {
return $model->exists && isset($freshModels[$model->getKey()])
? $freshModels[$model->getKey()] : null;
return $this->filter(function ($model) use ($freshModels) {
return $model->exists && isset($freshModels[$model->getKey()]);
})
->map(function ($model) use ($freshModels) {
return $freshModels[$model->getKey()];
});
}

Expand Down
11 changes: 8 additions & 3 deletions tests/Database/DatabaseEloquentIntegrationTest.php
Expand Up @@ -1340,10 +1340,15 @@ public function testFreshMethodOnCollection()
EloquentTestUser::find(1)->update(['name' => 'Mathieu TUDISCO']);
EloquentTestUser::find(2)->update(['email' => 'dev@mathieutu.ovh']);

$this->assertEquals($users->map->fresh(), $users->fresh());
$this->assertCount(3, $users);
$this->assertNotEquals('Mathieu TUDISCO', $users[0]->name);
$this->assertNotEquals('dev@mathieutu.ovh', $users[1]->email);

$users = new Collection;
$this->assertEquals($users->map->fresh(), $users->fresh());
$refreshedUsers = $users->fresh();

$this->assertCount(2, $refreshedUsers);
$this->assertEquals('Mathieu TUDISCO', $refreshedUsers[0]->name);
$this->assertEquals('dev@mathieutu.ovh', $refreshedUsers[1]->email);
}

public function testTimestampsUsingDefaultDateFormat()
Expand Down
8 changes: 6 additions & 2 deletions tests/Integration/Database/EloquentCollectionFreshTest.php
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\Fixtures\User;
Expand Down Expand Up @@ -30,8 +31,11 @@ public function testEloquentCollectionFresh()

$collection = User::all();

User::whereKey($collection->pluck('id')->toArray())->delete();
$collection->first()->delete();

$this->assertEmpty($collection->fresh()->filter());
$freshCollection = $collection->fresh();

$this->assertCount(1, $freshCollection);
$this->assertInstanceOf(EloquentCollection::class, $freshCollection);
}
}

0 comments on commit 914a203

Please sign in to comment.