V4n1ll4
V4n1ll4

Reputation: 6099

Laravel-5 get last inserted id after firstOrCreate()

I'm trying to get the last inserted ID in the database after a firstOrCreate() call. I have copied my code below:

$booking->firstOrCreate(array_slice($reserve->whereId($payment->reserved_place_id)->first()->toArray(), 0, 24))->save();

How can I get the last ID inserted?

I have looked at the other Laravel requests to get last insert ID but I believe this instance is different because they are not using firstOrCreate().

Thanks in advance.

Upvotes: 6

Views: 5229

Answers (2)

Fabio Antunes
Fabio Antunes

Reputation: 22882

// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

Returns always a model as stated in the Laravel documents:

There are two other methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew. The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.

$flight->id; //returns the last inserted id or the id of the already created document

Upvotes: 3

Martin Heralecký
Martin Heralecký

Reputation: 5789

firstOrCreate() method returns Model. So you can simply save it to some variable and then get the model's ID.

Upvotes: 9

Related Questions