3

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?

1
  • you can use ->get()->toArray(); Commented May 4, 2016 at 11:51

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for a set of great solutions! I forgot to mention in my question the scenario where there there is more than one note_id. I am trying to get DB::table('note_user')->select('note_id')->where('user_id', 1)->first()->note_id; to work with ->all() like this DB::table('note_user')->select('note_id')->where('user_id', 1)->all()->note_id; but it gives me an error "Call to undefined method Illuminate\Database\Query\Builder::all()". Is there a way to make this work with multiple note_id's?
I'm not sure if this will work, but try $notes = DB::table('note_user')->where('user_id', 1)->all('note_id'). If this isn't working, try get('note_id') instead. If this isn't working too, use Eloquent to use all(). When you got working solution, just iterate over the result collection with something like this foreach($notes as $note){ echo $note->note_id; }.
0

You could also try something like this, if you are using a model:

$department_id = Department::select('id')->where('dep_name','=', 'mydepartmentname')->first()->id;

$department_id - is the name of our variable we want to assign value from the database. Department is the model id - the part in the end is the field name in the table from which you you are drawing data. Hope this helps you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.