Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blade returns undefined offset

I've started learning PHP Laravel and I'm struggling a bit with something (probably quite trivial). When I render my page I see the following error:

ErrorException in BladeCompiler.php line 584: Undefined offset: 1

Controller

Located at \App\Http\Controllers\CompanyController.php

namespace App\Http\Controllers;

use App\Company;
use Illuminate\Http\Request;

class CompanyController extends Controller
{

    function index()
    {
        $companies = Company::all();

        // return $companies;
        return view('public.company.index', compact('companies'));
    }

}

View

Located at \App\resources\views\public\company\index.blade.php

@extends('public.layout')

@section('content')
    Companies
    @foreach $companies as $company
        {{ $company->title }}
    @endforeach
@stop

When I uncomment return $companies in my Controller I do have result, but .. I'm not sure why my - very simple - view isn't rendering. Who can help me out?

like image 213
meavo Avatar asked Nov 03 '16 21:11

meavo


3 Answers

The error point out that there was a issue while compiling blade file possibly because of syntax error. So, just wrap the foreach variable inside paranthesis and the issue should be fixed.

@extends('public.layout')

@section('content')
    Companies
    @foreach ($companies as $company)
        {{ $company->title }}
    @endforeach
@stop
like image 138
Saurabh Avatar answered Oct 10 '22 20:10

Saurabh


Check that $companies is set.

@extends('public.layout')

@section('content')
    @if(isset($companies))
        Companies
        @foreach $companies as $company
            {{ $company->title }}
        @endforeach
    @else
        {{-- No companies to display message --}}
    @endif
@stop
like image 33
Wistar Avatar answered Oct 10 '22 19:10

Wistar


This was driving me crazy. The problem was that I included in commented code something like this:

// Never ever should you have a @ in comments such as @foreach 
// The reason is the blade parser will try and interpret the @directive
// resulting in a cryptic error: undefined index 1

I hope this helps someone. Spent too many hours commenting out all my @foreach in code only to find out that it was a directive in comments that was causing the issue in the first place.

like image 30
RyanNerd Avatar answered Oct 10 '22 20:10

RyanNerd