Getting last inserted id

Following approach can be done to get the last inserted id of a model.

Step 01: Using mass assignment in model with fillable for fields to be inserted to tbl

protected $fillable = ['name', 'is_popular'];


Step 02: In controller, using create method of model to insert fields and getting last inserted id through the returned reference of model

$category = Category::create(['name'=>'demo from script','is_popular' => 1]);
// getting last inserted id
dd($category->id);


Another Approach: Only Step without mass assignment

$category = new Category();
$category->name = 'demo from script';
$category->is_popular = 1;
$category->save();
// getting last inserted id
dd($category->id);


Above snippet, mass assignment in model is not needed. Using save method in controller for a resource will help to insert required fields into tbl and then getting last inserted id for the next purposes.

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent