FRESH VS REFRESH

Jan 13, 2024 Copy Link

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.

Share via

Filed in:

Tips Eloquent
Mahmoud Ramadan

Mahmoud Ramadan

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

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE