Arthur Tarasov Arthur Tarasov - 7 months ago 30
SQL Question

How to return an integer from MySQL DB query in Laravel 5

In my Laravel controller I use the following code:

$usernotes = DB::select('SELECT note_id FROM note_user WHERE user_id = 1');


This is supposed to fetch the
note_id
from my many-to-many table, and it does. But
return $usernotes;
outputs

[{"paper_id":15}]


This looks like an array or a string, but I just need a plain integer
15
so I can put it into something like

$somevariable = someModel::find($usernotes)


$usernotes
doesn't look like a number and running the above line gives me an error:


ErrorException in helpers.php line 740: Object of class stdClass could
not be converted to string


How can I return just that number
15
out of that string?

Answer

When you're running the query, you're getting a collection of objects. To get the ID, you need to get property of one of those objects. So try this:

$id = $usernotes->first()->note_id; // or maybe this will work $id = $usernotes[0]->note_id;

Or this:

DB::table('note_user')->select('note_id')->where('user_id', 1)->first()->note_id;

If you're using a model:

NoteUser::find(1)->note_id;