how to get last insert id in laravel ^7.4.0

Hey i m using the only new data add in my current data base table and get the last id means insertid auto increament id in the database define and get the done of the laravel 8 code usefull ..

Mycontroller.php

 public function add_to_booking(Request $request) {
        $rule = [
            'trainee_id' => 'required',
            'plan_id' => 'required',
        ];

        $this->Required_params($request, $rule);

        $trainee_id = $request->input('trainee_id');
        $plan_id = $request->input('plan_id');


        $tbl_user_booking = new tbl_user_booking;
        $tbl_user_booking->trainee_id = $trainee_id;
        $tbl_user_booking->plan_id = $plan_id;
        $tbl_user_booking->user_id = $userId;
        $tbl_user_booking->save();

       return Response::json(array('success' => 1), 200);
    }

how to get last insert id in laravel to the model define

tbl_user_booking.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class tbl_user_booking extends Model {

 
    protected $table = 'tbl_user_booking';
    public $timestamps = false;
    protected $primaryKey = 'booking_id';

  

}

My last id is the “booking_id” and get the harm ful done.

how to get last insert id in laravel

Above image My autoincrement id is the “booking_id”

I want to return the last ID inserted but I don’t know how to get it. how to get last insert id in laravel

$tbl_user_booking->save();
$tbl_user_booking->booking_id;


$lastinsertid = $tbl_user_booking->booking_id;

echo $lastinsertid;

Response this like:

   "data": {
        "trainee_id": "5",
        "plan_id": "1",
        "user_id": 1,
        "booking_id": 2
    }

Leave a Comment