Chriz74
Chriz74

Reputation: 1480

sending model to view along id after save() in laravel

In my controller I am defining a model and persisting it to the DB with save() :

$model = new Model();

$model->attrib = "something";

$model->save();

Ok so now I want to send this newly created data to my view like this:

return view('new_model', ['new_model' => $model]);

The problem is the data passes to the view but not the id assigned to the model in the DB. How can I possibly send this data without performing a new query to the DB after the save(); Shouldn't the $model->save(); save to the DB and return what it persisted in the DB along id and all the stuff?

I stand corrected, the id was appearing at the end of the data.

Upvotes: 0

Views: 280

Answers (2)

Binal Gajjar
Binal Gajjar

Reputation: 322

Eloquent allows you to fill models by passing an associative array with values, and the keys representing the column names.

$model = Model::create([
  'attrib' => 'something',
]);

You will get the id by $model->id.

Hope it works. :)

Upvotes: 0

enno.void
enno.void

Reputation: 6579

$model->id should be the last id inserted.

Upvotes: 2

Related Questions