WHEN TO USE FRESH VS REFRESH

Jan 13, 2024

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.


AI Assistant

Choose AI provider

Text Tools

Make content clear and easy to read

Ask a Question

Get clear answers based on this content

0/500
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.