Search code examples
phpmysqllaraveleloquentnested-loops

Undefined offset: 1 in CompilesLoops.php laravel 5


I have a services list. Now I want to add sub-services to services list. I have two tables 'services' and 'sub-services' with foreign key constraint 'service_id'. Now, I want to show the 'services' and related 'sub-services' in master.blade.php. For services it was working fine, but, when trying with sub-services then getting this error. Would someone please help to get the expected result. In master.blade.php-

<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown"> Services</a>
      <ul class="dropdown-menu services-dropdown" role="menu">
         @forelse(App\Model\Service::all() as $service)
           <li class="dropdown-submenu">
              <a href="{{ url('services/'.$service->slug) }}">{{ $service->title }}</a>
                 <ul class="dropdown-menu sub-services">
                   @foreach(App\Model\SubService::where('service_id', '=',$service->id)->get()) as $subservice)
                     <li>
                       <a href="{{ url('sub-services/'.$subservice->slug) }}">{{ $subservice->title }}</a>
                     </li>
                   @endforeach
                  </ul>
           </li>
         @empty

         @endforelse
      </ul>
</li>

Two tables are here- 1.Services table service

2.Sub-services table sub-service


Solution

  • You're using the wrong syntax. You're using redundant ) near the get(), so change it to:

    @foreach(App\Model\SubService::where('service_id', $service->id)->get() as $subservice)
    

    Also, as I say in my best practices repo, you shouldn't execute queries in a Blade template. Consider moving the logic to a controller.