danielmz02
danielmz02

Reputation: 55

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

Upvotes: 1

Views: 2471

Answers (5)

Jithesh Jose
Jithesh Jose

Reputation: 1814

Create will return object of Laptop model.

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

$id = $laptop->id;

OR

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

Upvotes: 4

Avni
Avni

Reputation: 126

$id = Laptop::lastInsertId();

or

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

Upvotes: 1

Ankur Mishra
Ankur Mishra

Reputation: 1296

The create method returns the saved model instance. So use it link this:

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

$id = $laptop->id; 

$id is required id of newly added data.

Upvotes: 1

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

To get recently Added id you may follow this code

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

$id = $laptop->id;  //You get recently added id
echo $id;

Upvotes: 1

MrEvers
MrEvers

Reputation: 1072

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

$id = $laptop->id;

Upvotes: 1

Related Questions