Search code examples
phplaravelinsertlastinsertidlast-insert-id

How to get the last insert ids from laravel 4


I am using laravel 4. I have a table called documents. I am inserting data in the Document table using Document::insert() function. My code is given below

$statuses = array();
foreach($content as $i){
    array_push($statuses, array(
        'user_id' => $user->id,
        'document' => $i->text
    ));
}
$users = Document::insert($statuses);

Now I want to get the insert ids. But the $users variable only gives me a boolean variable called true. How can I get the insert ids.


Solution

  • Use insertGetId()

    If the table has an auto-incrementing id, use insertGetId to insert a record and retrieve the id

    Code Snippet

    $id = DB::table('Document')->insertGetId($yourarray);
    

    Note: When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id".