How to Get Last Inserted ID in Laravel?
Hello Artisan,
This is a short guide on get last inserted id in laravel. This example will help you get last inserted id from table in laravel. We will look at an example of how to get last inserted id in laravel. you'll learn laravel get last inserted id example.
,when you create database,you many a time use primary key column using the AUTO_INCREMENT attribute that means when you insert new record into the table then value of primary key column will be auto-increment with unique integer.
Whenever you perform an INSERT or UPDATE on database table with an AUTO_INCREMENT column then you get the last insert id of last insert or update query.
In PHP, you use mysqli_insert_id to get last inserted record id.
In laravel, when you go with DB query builder then you can use insertGetId() that will insert a record and then return last inserted record id.
Example 1:
public function getLastInsertedId()
{
$id = DB::table('users')->insertGetId(
['email' => '[email protected]', 'name' => 'Mehul']
);
dd($id);
}
Example 2:
public function getLastInsertedId()
{
$user = User::create(['name'=>'Mehul' , 'email'=>'[email protected]']);
dd($user->id);
}
It will help you...
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial