When you insert any record in database, you may want to insert other tables for the current inserted recorded id. So when you insert record, you will need to know what is the id of inserted record.
In this article, I will give you example of how you can get last inserted record's id in laravel 8. You can get laravel 8 get last inserted record id with following example in controller.
If you are using query builder, you may use use insertGetId()
method which insert the record and returns id of record.
/**
* create new instance of the class
*
* @return void
*/
public function create()
{
$id = \DB::table('users')->insertGetId([
'email' => '[email protected]',
'name' => 'Harsukh Makwana',
]);
dd($id); // 5
}
And here is example with eloquent query. create()
method returns the last inserted record object. So you can access object property as below:
use App\Models\User;
/**
* create new instance of the class
*
* @return void
*/
public function create()
{
$user = User::create([
'email' => '[email protected]',
'name' => 'Harsukh Makwana',
]);
dd($user->id); // 5
}
I hope it will help you. Thank you for reading article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to create Sitemap Format
Sitemap is a blueprint of your website t...Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
Sometimes when you are working apt-get c...How do I ask for Location Permissions in Javascript
In this article, we will share with you...Get The Difference Between Two Date In Laravel Using jpmurray/laravel-countdown
Today, Laravelcode share with you how to...Create HTTP requests to communicate with other websites in laravel
Larave is adding new features to its new...