rur2641 rur2641 - 1 month ago 4
PHP Question

How to get the difference between a query builder instance and an array of same instance

How to get the differencce between a query builder instance of a Model table and an array of objects of same model?

foreach ($completed_course_id as $value)
{
array_push($completed_courses,DB::table('courses')->where('id', $value)->first());
}
$courses = Course::all();
$result = array_diff($courses, $completed_courses);


Passing result as compact returns "array_diff(): Argument #1 is not an array"

Answer

Course::all() will return you a Illuminate\Database\Eloquent\Collection object which provides you vast amount of helper methods to iterate through arrays.

So instead of array_diff($courses, $completed_courses);, you would need to first convert the $courses to array by calling $courses->toArray():

$result = array_diff($courses->toArray(), $completed_courses);

On a side note, what the code above that is trying to achieve is probably won't going to work since you are doing array_diff on a series of objects! It's also inefficient to loop the $completed_course_id and query it one by one. I'm assuming your aim here is to retrieve all the incomplete courses. To do this, you can simply use this to replace all of the codes above:

$result = DB::table('courses')
    ->whereNotIn('id', $completed_course_id)->get();
Comments