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

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

亲切的问候!


当前回答

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

其他回答

使用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

您可以很容易地获取最后插入的记录Id

$user = User::create($userData);
$lastId = $user->value('id');

从DB中最后插入的记录中获取Id是一个很棒的技巧。

你可以这样做:

$result=app('db')->insert("INSERT INTO table...");

$lastInsertId=app('db')->getPdo()->lastInsertId();

在laravel 5中:你可以这样做:

use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
    private $user;
    public function  __construct( User $user )
    {
        $this->user = $user;
    }
    public function store( UserStoreRequest $request )
    {
       $user= $this->user->create([
            'name'              => $request['name'],
            'email'             => $request['email'],
            'password'          => Hash::make($request['password'])
        ]);
        $lastInsertedId= $user->id;
    }
}

在save $data之后->save()。所有数据都被推入$data内。因为这是一个对象,当前行刚刚保存在$data中。所以last insertId将在$data->id中找到。

响应代码为:

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