So I have a list of about 1700 records and I want to show it paginated with five records per page and for the most part this is working with the code I have currently. The problem I am having is that when I go to certain pages I get this error: Undefined offset: 0 (View: Project\resources\views\minors\index.blade.php)
. When I var_dump
the data I send to the view it contains an item with the index 0.
Controller method:
public function index( Request $request )
{
$locations = Location::all();
$minors = Module::paginate(5);
return view('minors.index')->with(compact('minors','locations'));
}
View:
@if(isset($minors))
@foreach($minors as $key => $minor)
<a id="minorLinkId" class="minorLink" href="{{ Action('MinorController@show', $minor->id) }}">
<div id="minorContainerId" class="minorContainer">
<div class="textContainer">
<h3>{{$minor->name}}</h3>
<p>{{@strip_tags($minor->subject)}}</p>
</div>
<div class="imageContainer">
<img src="{{asset('img/person-placeholder.jpg')}}">
<ul>
<li>ECTs: {{$minor->ects}}</li>
<li>Taal: {{$minor->language}}</li>
<li>Niveau: {{$minor->level}}</li>
<li>{{$minor->locations[0]->Name }}</li>
</ul>
</div>
</div>
</a>
@endforeach
{{ $minors->links() }}
@endif
First part of var_dump($minors)
placed before return view('minors.index')
in the index method of the controller:
object(Illuminate\Pagination\LengthAwarePaginator)#486 (11) { ["total":protected]=> int(1710) ["lastPage":protected]=> int(342) ["items":protected]=> object(Illuminate\Database\Eloquent\Collection)#479 (1) { ["items":protected]=> array(5) { [0]=> object(App\Module)#478 (26) { ["guarded":protected]=> array(0) { } ["connection":protected]=> string(5) "mysql" ["table":protected]=> string(7) "modules" ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(33) {
I suspect the problem has something to do with the return statement in the index method of the controller but I don't understand why it only happens on certain pages.
I appreciate the help.
The error is because of this line
<li>{{$minor->locations[0]->Name }}</li>
You are trying to access the index zero which does not exist because the locations array is empty or undefined. You can replace the above code with the following code:
@if(sizeof($minor->locations) > 0)
<li>{{$minor->locations[0]->Name }}</li>
@endif
The sizeof() function counts elements in an array or properties in an object. It returns the number of elements in an array.