Let's demonstrate the difference between the `fresh` and `refresh` methods
The core difference is that the `refresh` method copies the model instance by REFERENCE.
use App\Models\User;
use Illuminate\Support\Facades\Route;
Route::get('fresh', fn () => User::first()->freshCurrentUser());
Route::get('refresh', fn () => User::first()->refreshCurrentUser());
Initially, let's check out the `fresh` method:
/**
* Freshes the current user instance with fake data.
*/
public function freshCurrentUser()
{
$fakeName = fake()->name;
$this->name = $fakeName;
// Fresh the current instance from the database
$fresh = $instance->fresh();
$fresh->name = 'Name: ' . $fakeName;
$fresh->save();
// {
// "fakeName": "Mrs. Neha Smitham"
// "instance": {
// "name": "Mrs. Neha Smitham"
// },
// "fresh": {
// "name": "Name: Mrs. Neha Smitham"
// }
// }
}
In addition, we shall monitor the `refresh` method:
/**
* Refreshes the current user instance with fake data.
*/
public function refreshCurrentUser()
{
...
// Refresh the user instance
$refresh = $instance->refresh();
$refresh->name = 'Name: ' . $fakeName;
$refresh->save();
// {
// "fakeName": "Mrs. Neha Smitham",
// "instance": {
// "name": "Name: Mrs. Neha Smitham"
// },
// "refresh": {
// "name": "Name: Mrs. Neha Smitham"
// }
// }
}
You may have noticed from the previous responses that the instance and refresh are equal whereas the instance and fresh are not, meaning the instance and refresh have copied by REFERENCE.