I have many to many relation for categories and products. In a specific category page I want to add pagination for products.
This is my code in Category model:
public function products() { return $this->belongsToMany(Product::class, 'category_product', 'category_id', 'product_id' ) ->where('is_published',1) ->orderBy('id','ASC')->paginate(5); }
This is CategoryController code:
public function show($id) { $category = Category::findorfail($id); return view(category.show, compact('category'); }
This is a pagination code in category view blade:
{{ $products->links() }}
This is an error I’m getting:
AppModelsCategory::products must return a relationship instance.
Any solutions?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The error message is pretty obvious, The relationship method must return a relationship instance. So these two are gonna work because those return an instance of type IlluminateDatabaseEloquentRelationsBelongsToMany
class:
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
);
}
// Or
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
)
// This update the internal query of the relationship instance to query the relationship later on.
->where('is_published',1)->orderBy('id','ASC');
}
Your code will return an instance of IlluminatePaginationLengthAwarePaginator
, which is NOT gonna work:
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
)
->where('is_published',1)
->orderBy('id','ASC')->paginate(5);
}
Then in your controller, you can do something like:
class CategoriesController extends Controller
{
public function show($id)
{
$category = Category::findOrFail($id);
$products = $category->products()->paginate(5);
return view('categories.show', compact('category', '$products'));
}
}
Method 2
Found a solution for this:
CategoryController:
public function show($id) { $category = Category::findorfail($id); $category->setRelation('products', $category->products()->paginate(5)); return view(category.show, compact('category'); }
View blade:
@foreach($category->products as $product) {{ $product->title }} @endforeach {!! $category->products->render() !!}
Category model:
public function products() { return $this->belongsToMany(Product::class, 'category_product', 'category_id', 'product_id' ) ->where('is_published',1) ->orderBy('id','ASC'); }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0