Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Get Record ID from Update Query

Tags:

mysql

laravel

For this update query, I'm trying to get the id after I run it.

$results = DB::table('testDB123.users')
    ->where('fbID', '=', $x['id'])
    ->update([
            'updated_at' => $x['currDate'],
            'fbFirstName' => $x['firstName'],
            'fbLastName' => $x['lastName']
        ]
    );

Tried this with no luck $results->id

Is there anything similar to insertGetId for update queries?

$id = DB::table($table1)->insertGetId([...])
like image 579
xx7xx7xx Avatar asked Jan 13 '17 00:01

xx7xx7xx


1 Answers

update() method doesn't return an object, so you have two options:

Option 1

Use updateOrCreate():

$user = User::updateOrCreate(['fbID' => $x['id']], $dataArray);
$id = $user->id;

Option 2

Get an object and update it:

$user = User::where('fbID', '=', $x['id'])->first();
$user->update($dataArray);

$id = $user->id;
like image 51
Alexey Mezenin Avatar answered Oct 18 '22 14:10

Alexey Mezenin