Wildfire
Wildfire

Reputation: 192

PHP / Laravel : Retrieve new info of Model after save()

Here's my issue : I have a table in sqlserver database as follow :

Product ( 
 id int identity,
 reference varchar(12),
 name varchar(40)
)

In a web page of a laravel web-app, I got a form with name only as field and a submit button. In DB side, I created a trigger (Instead of insert) that updates the reference of the row based on the generated id. Example :

RGX0000123

Where 123 is the generated ID and RGX is randomly generated.

The flow follows Post/Redirect/Get design pattern. After the submit, I want to redirect to a page where the reference is shown in the URL and not the ID.

In laravel's controller, I save my object with Eloquent and redirect to the next page :

$product->save();
return redirect()->route('next_page', ['reference' => $product->reference]);

My problem is that I can get the id after the save but not the reference. I don't know how Eloquent works but with Hibernate(JAVA) such thing can be resolved with a session.flush() to sync the object with data from the database.

Quick and dirty fix was using

$product= Product::find($product->id);

Is there a cleaner way to handle this ?

Upvotes: 10

Views: 11475

Answers (2)

Kenny Horna
Kenny Horna

Reputation: 14251

Refresh the object instead:

$product->save();
$product->refresh(); // <---

return redirect()->route('next_page', ['reference' => $product->reference]);

From the documentation:

Refreshing Models

You can refresh models 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 = App\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 = App\Flight::where('number', 'FR 900')->first();

$flight->number = 'FR 456';

$flight->refresh();

$flight->number; // "FR 900"

Upvotes: 24

Levon Babayan
Levon Babayan

Reputation: 282

You can use refresh() method for refresh data in model

$model->refresh();

Upvotes: 1

Related Questions