我目前正在使用下面的代码在一个表中插入数据:

<?php

public function saveDetailsCompany()
{
    $post = Input::All();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    if ($data->save()) {
        return Response::json(array('success' => true), 200);
    }
}

我想返回插入的最后一个ID,但我不知道如何获取它。

亲切的问候!


当前回答

有几种方法可以获取最后插入的id。所有这些都是基于您在插入时使用的方法。在这种情况下,你可以得到最后一个。

$data->save();
$data->id;

对于其他人谁需要知道如何获得最后插入id,如果他们使用其他插入方法,这里是如何:

使用create()方法 书=书:美元:创建(['名字' = > ' Laravel战士']); $lastId = $book->id; 使用insertGetId () $id = DB::table('books')->insertGetId(['name' => 'Laravel warrior']);$lastId = $id; 使用lastInsertId()方法 $lastId = DB::getPdo()->lastInsertId();

参考https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/

其他回答

public function store( UserStoreRequest $request ) {
    $input = $request->all();
    $user = User::create($input);
    $userId=$user->id 
}

保存模型后,初始化实例的id为:

$report = new Report();
$report->user_id = $request->user_id;
$report->patient_id = $request->patient_id;
$report->diseases_id = $request->modality;
$isReportCreated = $report->save();
return $report->id;  // this will return the saved report id

For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...

public function store() {

    $input = Request::all();
    $id = Company::create($input)->id;

    return redirect('company/'.$id);
}

这就是它是如何为我工作的,family_id是自动增量的主键,我使用Laravel7

    public function store(Request $request){
        $family = new Family();
        $family->family_name = $request->get('FamilyName');
        $family->family_no = $request->get('FamilyNo');
        $family->save();
        //family_id is the primary key and auto increment
        return redirect('/family/detail/' .  $family->family_id);
    }

同样在Model Family文件中,应该将增量设置为true,否则上面的$ Family——>family_id将返回空

    public $incrementing = true;
  

可选方法为:

$lastID = DB::table('EXAMPLE-TABLE')
                ->orderBy('id', 'desc')
                ->first();

$lastId = $lastProduct->id;

来自Laravel 5.8版本