In Laravel, you can retrieve the last inserted ID from a database table using the insertGetId()
method. This method not only inserts a record into the table but also returns the ID of the last inserted record. Here's an example:
Example 1:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$id = DB::table('users')->insertGetId([
'name' => 'Alen',
'email' => 'alen@example.com',
'password' => 'secret',
]);
// $id will now contain the ID of the last inserted record
dd($id);
}
}
Example 2:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$create = User::create([
'name' => 'Alen',
'email' => 'alen@example.com',
'password' => 'secret'
]);
$id = $create->id;
dd($id);
}
}