Posts Learn Components Snippets Categories Tags Tools new About

How to Get Last Inserted Eloquent ID in Laravel

Learn how to get the last inserted ID using Laravel eloquent and perform an action based on the ID

Created on Oct 01, 2021


After saving data to the database, oftentimes you need to get the ID right away to perform some action and even processing. To get the ID of the last inserted record, you can right away access the data that's returned by the method used for inserting.

Method 1: Getting Last Inserted Record ID

For this example, let's imagine you are creating a new "Post" model, and to get the ID of the last inserted post you can call the "id" from the model instance like in the example below. 

$post = Post::create(['title' => 'hello world']);

$post->id; // you can right away access the ID

// if you prefer to use the save() method then it will be like below
$post = new Post();

$post->title = 'hello world';


$id = $post->id; // this will retrieve teh id

Method 2: Using insertGetId to get Latest ID

Another way to get the ID is by using the "insertGetId()" method and this method will create a new record and right away return the "id" to the variable.

$id = \DB::table('posts')->insertGetId(['title' => 'hello world 2']);
The code above will create a new post and then return the post ID to the user.

Method 3: Using lastInsertId to get Latest ID

One other way is to use "lastInsertId()" method after chaining the "getPdo()" of the DB facade and the code example will be as follows.

$id = DB::getPdo()->lastInsertId();

Perform Action with Last Inserted ID

Now that you have the ID you can use it to redirect the user to any of the respective pages or even return it to the client if you are sending it as a JSON response.

$post = Post::create(['title' => 'hello world']);

return redirect()->route('', ['id' => $post->id]);
For the JSON response, you can pass it like below.

$post = Post::create(['title' => 'hello world']);

return response()
    ->json(['success' => true, 'last_insert_id' => $data->id], 200);

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️