How To Get Last Inserted ID In Laravel 5

By : PHPErrorCode April 17, 2018 944 Views laravel

Today I will show you how to get the last instant id in Laravel web application, If you are looking for it, then there are many ways to get the last insert id, we use the different methods to get the Last insert id in laravel framework.

Most commonly the following five methods are used......

  1. lastInsertId()
  2. insertGetId()
  3. create()
  4. save()
  5. updateTable

(1) Using lastInsertId() method

when you go with DB query builder then you can use lastInsertId() laravel method that will insert a record and then return last inserted record id.

Example:


public function addUser()
{
	$data['name'] = 'Jacob'
	$data['email'] = 'Jacob@gmail.com'

    $user_id = DB::table('users')->lastInsertId($data);

	dd(user_id);
}

2) Using insertGetId() method

when you go with DB query builder then you can use insertGetId() laravel method that will insert a record and then return last inserted record id.

You need PDO object to run this method

Example:


public function addUser()
{
	$data['name'] = 'Sophia'
	$data['email'] = 'Sophia@gmail.com'

    $user_id = DB::table('users')->insertGetId($data);

	dd(user_id);
}

3) Using create() method.

when you go with DB query builder then you can use create() laravel method that will insert a record and then return object last inserted ID.

Example:


public function addUser()
{
	$data['name'] = 'William'
	$data['email'] = 'William@gmail.com'

    $user = User::create($data);

	dd($user->id);
}

4) Using save() method.

when you go with DB query builder then you can use save() laravel method that will insert a record and then return last inserted record id.

Example:


public function addUser()
{

    $data = new User;
	$data->name = 'William';
	$data->email = 'William@gmail.com';
	$data->save();

	dd($user->id);
}

5) Using updateTable() method

when you go with DB query builder then you can use updateTable() laravel method that will insert a record and then return last inserted record id.

Example:


public function addUser()
{
	$data['name'] = 'Sophia'
	$data['email'] = 'Sophia@gmail.com'

    $user_id = Table::updateTable($data);

	dd(user_id);
}


Comment