Here's a quick blog post explaining the differences between fresh()
and refresh()
on Eloquent models.
Let's assume we have a Team model in hand represented by the $team
variable.
In Laravel, both $team->fresh()
and $team->refresh()
are used to reload the data associated with a model from the database. However, there is a subtle difference between them in terms of how they are used:
-
$team->fresh()
:-
$team->fresh()
is a more explicit way to reload the model's data from the database. - It returns a new instance of the model with the data from the database, leaving the original model unchanged.
- It's useful when you want to obtain a fresh instance of the model without modifying the existing one.
-
Example:
$freshTeam = $team->fresh();
// $team remains unchanged, and $freshTeam
// contains the refreshed data
-
$team->refresh()
:-
$team->refresh()
is a method that directly refreshes the data of the existing model in-place. - It modifies the current instance of the model, updating its attributes with the data from the database.
- This can be useful when you want to refresh the data of the current model without creating a new instance.
-
Example:
$team->refresh();
// $team is updated with the refreshed data
In summary, the key difference is that $team->fresh()
returns a new instance with fresh data, while $team->refresh()
updates the existing instance in-place. The choice between them depends on whether you want to work with a new copy of the model or update the existing one.
Top comments (1)
Thanks man! that just helped me with something I was struggling!