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

<?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,但我不知道如何获取它。

亲切的问候!


当前回答

使用insertGetId同时插入和获取插入id

从医生

如果表有一个自动递增的id,则使用insertGetId方法 插入一条记录,然后检索ID:

通过模型

$id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);

通过DB

$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);

详情请访问:https://laravel.com/docs/5.5/queries#inserts

其他回答

使用雄辩的模型

use App\Company;

public function saveDetailsCompany(Request $request)
{

$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

// Last Inserted Row ID

echo $createcompany->id;

}

使用查询生成器

$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

echo $createcompany->id;

获取Laravel中最后插入行id的更多方法:http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel

你也可以这样尝试:

public function storeAndLastInrestedId() {
    $data = new ModelName();
    $data->title = $request->title;
    $data->save();

    $last_insert_id = $data->id;
    return $last_insert_id;
}

你可以使用$this构造函数变量在当前函数或控制器中实现“使用Laravel Eloquent最后插入Id”(不添加任何额外列)。

public function store(Request $request){
    $request->validate([
        'title' => 'required|max:255',
        'desc' => 'required|max:5000'
    ]);

    $this->project = Project::create([
        'name' => $request->title,
        'description' => $request->desc,
    ]);

    dd($this->project->id);  //This is your current/latest project id
    $request->session()->flash('project_added','Project added successfully.');
    return redirect()->back();

}

保存后,$data->id应该是最后插入的id。

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

可以这样使用。

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);

更新laravel版本试试这个

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);

这里有一个例子:

public static function saveTutorial(){

    $data = Input::all();

    $Tut = new Tutorial;
    $Tut->title = $data['title'];
    $Tut->tutorial = $data['tutorial'];   
    $Tut->save();
    $LastInsertId = $Tut->id;

    return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}