Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Collection after update()?

Using Raw, how to return collection of updated row?

For example:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

I was expecting dd($updated) to return updated row of collection but it returned 1.

{{$updated->votes}} should return 123
like image 202
I'll-Be-Back Avatar asked Mar 29 '17 12:03

I'll-Be-Back


2 Answers

Try this

$updated = tap(DB::table('users')->where('id', 1))
    ->update(['votes' => 123])
    ->first();

like image 171
PW_Parsons Avatar answered Oct 04 '22 16:10

PW_Parsons


That's not how it works. You can't expect this query will return you an object:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

If you want to use Query Builder only as you mentioned in your question, you'll need to get an object manually:

$data = DB::table('users')->where('id', 1)->first();

With Eloquent you can use the updateOrCreate():

$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);

This will return an object. update() will return boolean, so you can't use it here.

like image 37
Alexey Mezenin Avatar answered Oct 04 '22 16:10

Alexey Mezenin