3 Methods to get Last inserted row ID in Laravel

In this post i will listed 3 methods for to get last inserted row ID in Laravel.

For Ex : we add new row in Booking table and get Last Inserted Id.

save() Method

To create a new record in the database, create a new model instance, set attributes on the model, then call the save method:

use App\Booking;

$newbooking = new Booking;

$newbooking->fromdate = '2018-06-25';

$newbooking->todate = '2018-06-26';

$newbooking->roomno = 5;

$newbooking->userid = Auth::user()->id;

$newbooking->save();

echo $newbooking->id;

create() Method

Once we have made the attributes mass assignable, we can use the create method to insert a new record in the database. The create method returns the saved model instance:

use App\Booking;

$newbooking = Booking::create(['fromdate' => '2018-06-25','todate'=>'2018-06-26','roomno'=>5,'userid'=>Auth::user()->id]);

echo $newbooking->id;

insertGetId() Method

this method to insert a record and then retrieve the Last Inserted ID

$newbooking = DB::table('booking')->insertGetId(['fromdate' => '2018-06-25','todate'=>'2018-06-26','roomno'=>5,'userid'=>Auth::user()->id]);

echo $newbooking;

you can use it and get last ID of inserted record in your laravel application.

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *