Skip to content
Advertisement

Laravel get ID of newly created resource

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

Advertisement

Answer

$id = Laptop::lastInsertId();

or

$id = Laptop::create([
    'user_id' => 1,
    'name' => $request->name,
    'brand' => $request->brand,
    'SN' => $request->SN,
    'price' => $request->price
])->id;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement