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.
<?php $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'; $post->save(); $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.
<?php $id = \DB::table('posts')->insertGetId(['title' => 'hello world 2']);
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.
<?php $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.
<?php $post = Post::create(['title' => 'hello world']); return redirect()->route('posts.show', ['id' => $post->id]);
<?php $post = Post::create(['title' => 'hello world']); return response() ->json(['success' => true, 'last_insert_id' => $data->id], 200);
Leave a reply