Reputation: 1353
I'm getting grade_id from the database:
$grade_id = DB::table('grades')->where('teacher_id',$teacher_id)->select('grade_id')->get();
and then I want to use that grade_id array in the where eloquent clause so I run
$home_feed = Home::join('home_grade', 'home_grade.home_id', '=', 'homes.id')
->whereIn('grade_id', $grade_id)
->get();
but when I run this I'm getting an error: Object of class stdClass could not be converted to string
What could be the problem? Thanks guys.
Upvotes: 2
Views: 5455
Reputation: 5896
You need to create the array correctly. To do this use two functions that Eloquent work with: pluck()
and toArray()
. Look at example below:
$grade_id = DB::table('grades')->where('teacher_id',$teacher_id)->pluck('grade_id')->toArray();
Upvotes: 0
Reputation: 31812
Depending on laravels version your $grade_id
is either an array or a collection of objects. What you need is an array or a collection of values.
You can achieve that using the pluck()
method insted of select()
like IzzEps suggested.
But you can get the same result by passing a subquery to the whereIn()
method:
$gradeSubquery = DB::table('grades')->where('teacher_id',$teacher_id)->select('grade_id');
$home_feed = Home::join('home_grade', 'home_grade.home_id', '=', 'homes.id')
->whereIn('grade_id', $gradeSubquery)
->get();
This way you will run only one query instead of two.
Update: Before version 5.2 you have to use lists()
instead of pluck()
. And the whereIn()
method doesn't accept a Builder
as second parameter. To get the same query you would need to use a closure:
$home_feed = Home::join('home_grade', 'home_grade.home_id', '=', 'homes.id')
->whereIn('grade_id', function($query) use($teacher_id) {
$query->from('grades')
->where('teacher_id', $teacher_id)
->select('grade_id');
})
->get();
Upvotes: 2
Reputation: 1353
Using lists worked.
$grade_id = Grade::where('teacher_id', $teacher_id)->lists('grade_id');
They return an array instead of a collection
Upvotes: 0
Reputation: 582
your first query is returning a collection, not the grade_id.
Try this instead: $grade_id = DB::table('grades')->where('teacher_id',$teacher_id)->pluck('grade_id');
Upvotes: 0