I have categories and items tables. Each item belongs to only one category and each category has many items. So, in Category model I defined this relationship:
public function items()
{ return $this->hasMany('Item', 'catid'); }
and I retrieve data for a category this way:
$category = Category::find($id);
return View::make('admin.categories.catdetails')->with('category', $category);
and in my view I can loop through data:
@foreach ($category->items as $item)
<tr>
<td> {{ $item->name }} </td>
<td> {{number_format($item->price, 2, '.', '')}} </td>
</tr>
@endforeach
but this results in all items in on page. How to make use of laravel pagination in case that I have so many items for one page?? How can I use
::paginate() // in controller or model
->links() // in view
as, so far, it throws many errors and I can't figure it out. Thanks in advance.
You can call paginate()
on the relationship object, which you access by ->items()
(not ->items
)
$items = $category->items()->paginate(10);
return View::make('admin.categories.catdetails')
->with('category', $category)
->with('items', $items);
Then in your view:
@foreach ($items as $item)
And:
$items->links()
You could use an attribute accessor to achieve what you want. In your model:
public function getPaginatedItemsAttribute(){
return $this->items()->paginate(10);
}
And then you use it like this:
@foreach ($category->paginatedItems as $item)
And:
$category->paginatedItems->links()