Asked  7 Months ago    Answers:  5   Viewed   32 times

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

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

Kind regards!

 Answers

24

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

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

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
 
ChronoFish
answered 7 Months ago
100

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'   => [
        PDO::ATTR_EMULATE_PREPARES => true
    ]
],

Laravel 5.1. Hope it will help!

Wednesday, March 31, 2021
 
VitaCoco
answered 7 Months ago
77

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

$em->persist($user);
$em->flush();
$user->getId();
Wednesday, March 31, 2021
 
twk
answered 7 Months ago
twk
30

As described at http://laravel.com/docs/eloquent#mass-assignment, 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
 
cusejuice
answered 5 Months ago
68

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
 
Gerardo
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 :