Asked  7 Months ago    Answers:  5   Viewed   32 times

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


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

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

Kind regards!



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


Can be used like this.

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

For updated laravel version try this

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
Wednesday, March 31, 2021
answered 7 Months ago

It seems to work adding

'options'   => [
                PDO::ATTR_EMULATE_PREPARES => true

Inside projectName/config/database.php file in DB configuration. It will be like this:

'mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'forge'),
    'username'  => env('DB_USERNAME', 'forge'),
    'password'  => env('DB_PASSWORD', ''),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
    'options'   => [

Laravel 5.1. Hope it will help!

Wednesday, March 31, 2021
answered 7 Months ago

I had to use this after the flush to get the last insert id:

Wednesday, March 31, 2021
answered 7 Months ago

As described at, you need the $fillable property set for all the properties you want to be mass-assignable. You should therefore uncomment the line starting with protected $fillable = ....

Saturday, May 29, 2021
answered 5 Months ago

Use getGeneratedKeys() if your JDBC driver supports it. You don't want to muck around trying to get the key yourself after the insert. If your driver does not support getGeneratedKeys() then I would get the next value from the key before the insert.

Thursday, July 22, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :