https://laravel.com/docs/9.x/eloquent#refreshing-models
If you already have an instance of an Eloquent model that was retrieved from the database, you can " refresh " the model using the fresh and refresh methods. The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:
$flight = Flight::where('number', 'FR 900')->first();
$freshFlight = $flight->fresh();
The refresh method will re-hydrate the existing model using fresh data from the database . In addition, all of its loaded relationships will be refreshed as well:
$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number; // "FR 900"
All the time (regularly) I make my requests by querying the models and relations only once for a normal http request (eg post-redirect-get or simply for a get).
When should I reload the relation or model information?
I feel that I have done my requests wrong after seeing this part of the Laravel documentation.
Could you give me some use cases for fresh
()/ refresh
()? Please
Is there something that escapes my knowledge?
Fresh and refresh are used when your model might have been change since it's first query
exemple:
// The passenger is in the FR 900 Flight
$passenger = Passenger::with('flight')->find(1);
// dd($passenger->flight->number); => FR 900
$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->save();
// dd($passenger->flight->number); => FR 900
$passenger->flight->fresh(); // Refresh Only the flight
// OR
$passenger->refresh(); // Refresh The Passenger AND ALL his relationships (his flight)
// dd($passenger->flight->number); => FR 456
The fresh method will get only the model it's been called The refresh method will make a fresh() on the model and all it's loaded relationships
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.