Laravel Eloquent中Refreshing Models详解:fresh()与refresh()用法场景
Hey there! I totally get where you're coming from—Laravel's docs can feel a bit overwhelming when you're just getting your feet wet with Eloquent. Let's break down the Refreshing Models feature, walk through clear examples for fresh() and refresh(), and clarify exactly when to use each one.
Put simply, refreshing a model means pulling the latest version of that record directly from your database. This is super useful when the data in your database might have changed (like from another request, a queue job, or even manual edits in your DB tool) but the model instance in your code still has the old data.
The fresh() Method
The fresh() method creates and returns a brand new instance of your model with the latest database data. The original model instance you had stays untouched—its properties won't change at all.
Example:
// Grab a user from the database $user = App\Models\User::find(1); echo $user->name; // Output: "Old Name" // Now, let's say someone updates this user's name in the database directly (or via another process) // Use fresh() to get the latest data as a new instance $freshUser = $user->fresh(); echo $freshUser->name; // Output: "New Name" echo $user->name; // Still outputs: "Old Name" (original instance is unchanged)
The refresh() Method
Unlike fresh(), the refresh() method updates the current model instance's properties to match the latest database data. It doesn't return a new object—it modifies the one you're already working with.
Example:
// Grab the same user $user = App\Models\User::find(1); echo $user->name; // Output: "Old Name" // Update the user's name in the database (outside this code) // Refresh the current instance $user->refresh(); echo $user->name; // Now outputs: "New Name" (original instance is updated)
When to Use Which?
Let's break down the use cases clearly:
- Use
fresh()when: You need the latest data but want to keep the original model instance (with its old data) intact. For example, if you want to compare the old vs new values, or if you're not done working with the original state of the model. - Use
refresh()when: You want the model instance you're actively working with to reflect the latest database state immediately. This is great if all your subsequent code needs to use the most up-to-date data, and you don't need the old values anymore.
Quick Bonus Tip
Both methods can also take an array of specific attributes to refresh, if you don't need the entire model:
// Only refresh the 'name' and 'email' attributes $user->refresh(['name', 'email']); $freshUser = $user->fresh(['name', 'email']);
内容的提问来源于stack exchange,提问作者Punit khandelwal

