Home » Php » php – BadMethodCallException Method Illuminate\Database\Eloquent\Collection::paginate does not exist

php – BadMethodCallException Method Illuminate\Database\Eloquent\Collection::paginate does not exist

Posted by: admin February 25, 2020 Leave a comment

Questions:

After adding Paginate function I’m getting this error

$sub_categories = SubCategory::where('id', $id)->first();
$products = Products::where('subcategory_id', $sub_categories->id)->get()->paginate(10);
How to&Answers:

$sub_categories = SubCategory::where('id', $id)->first(), this will only give you null or one record, not a collection, so you can not use ->paginate(10); chain it. You will only get one record at the most, why you need to paginate?

Update
so first for the sub_categories you do not need to paginate, as you just want one record. so the code should be like this.

$sub_categories = SubCategory::where('id', $id)->first();

second, if you want to paginate $products you should do this,

if ($sub_categories)
{
    $products = Products::where('subcategory_id', $sub_categories->id)->paginate(10);
}