Arthur Tarasov Arthur Tarasov - 5 months ago 23x
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
from my many-to-many table, and it does. But
return $usernotes;


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

$somevariable = someModel::find($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
out of that string?


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: