使用 Laravel Eloquent 获取最后插入的 ID [英] Get the Last Inserted Id Using Laravel Eloquent

查看:28
本文介绍了使用 Laravel Eloquent 获取最后插入的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码在表中插入数据:

I'm currently using the below code to insert data in a table:

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

I want to return the last ID inserted but I don't know how to get it.

亲切的问候!

推荐答案

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

After save, $data->id should be the last id inserted.

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

可以这样使用.

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

对于更新的 Laravel 版本试试这个

For updated laravel version try this

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

这篇关于使用 Laravel Eloquent 获取最后插入的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆