Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - Return the id of the current insert

I have the following query

public static function createConversation( $toUserId )
{

    $now = date('Y-m-d H:i:s');
    $currentId = Auth::user()->id;

    $results = DB::table('pm_conversations')->insert(
        array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
    );

    return $results;

}

How would i return the id of the row just inserted?

Cheers,

like image 682
BigJobbies Avatar asked Jun 17 '13 03:06

BigJobbies


1 Answers

Instead of doing a raw query, why not create a model...

Call it Conversation, or whatever...

And then you can just do....

 $result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;

Which will return an id...

Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe

 $results = DB::table('pm_conversations')->insertGetId(
    array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);

This method requires that the id of the table be auto-incrementing, so watch out for that...

The last method, is that you can just return the last inserted mysql object....

Like so...

 $result = DB::connection('mysql')->pdo->lastInsertId();

So if you choose that last road...

It'll go...

public static function createConversation( $toUserId )
 {

$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;

$results = DB::table('pm_conversations')->insert(
    array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
 );


 $theid= DB::connection('mysql')->pdo->lastInsertId();
 return $theid;

 }

I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question. Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation

like image 112
Kylie Avatar answered Dec 14 '22 19:12

Kylie