Laravel get ID of newly created resource

Tags: , ,



So basically I am doing this:

Laptop::create([
    'user_id' => 1,
    'name' => $request->name,
    'brand' => $request->brand,
    'SN' => $request->SN,
    'price' => $request->price
]);

How do I save the ID of the newly created resource? Since the ID field is auto incrementing I don’t need to insert it manually. If for example the ID is 47, I need to be able to store the ID locally for use. Like store it in a variable named $ID

This is so I can create meta rows which contain information on the Laptop like Laptop parts. They all need a parent_id which would be the $ID

Answer

$id = Laptop::lastInsertId();

or

$id = Laptop::create([
    'user_id' => 1,
    'name' => $request->name,
    'brand' => $request->brand,
    'SN' => $request->SN,
    'price' => $request->price
])->id;


Source: stackoverflow