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

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

亲切的问候!


当前回答

你可以使用$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();

}

其他回答

这里有一个例子:

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);
}

获取数据库中最后插入的id 你可以使用

$data = new YourModelName;
$data->name = 'Some Value';
$data->email = 'abc@mail.com';
$data->save();
$lastInsertedId = $data->id;

这里$lastInsertedId会给你最后插入的自动增量id。

$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';   
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name

return Response::json(['success' => true,'id' => $recId], 200);

为劳拉***

首先创建一个对象,然后为该对象设置属性值,然后保存对象记录,然后获取最后插入的id。如

$user = new User();        

$user->name = 'John';  

$user->save();

//现在获取最后插入的id

$insertedId = $user->id;

echo $insertedId ;

保存模型后,初始化实例的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