Laravel获取新创建资源的ID

时间:2019-11-20 09:43:00

标签: php laravel laravel-6

所以基本上我正在这样做:

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

如何保存新创建的资源的ID?由于ID字段是自动递增的,因此不需要手动插入。例如,如果ID为47,则我需要能够将ID存储在本地以供使用。就像将其存储在名为$ID

的变量中一样

因此,我可以创建包含笔记本电脑上的信息(例如笔记本电脑部件)的元行。他们都需要有一个{_1}}

的parent_id

5 个答案:

答案 0 :(得分:2)

创建将返回Laptop模型的对象。

$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;

答案 1 :(得分:1)

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

$id = $laptop->id;

答案 2 :(得分:1)

要获取最近添加的ID,您可以遵循以下代码

$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;

答案 3 :(得分:1)

create方法返回保存的模型实例。所以用它链接:

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

$id = $laptop->id; 

$id是新添加的数据的必需ID。

答案 4 :(得分:1)

$id = Laptop::lastInsertId();

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