Blade returns 未定义的偏移量

Blade returns undefined offset

我已经开始学习 PHP Laravel 并且我正在努力解决一些问题(可能非常微不足道)。当我呈现我的页面时,我看到以下错误:

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

控制器

位于 \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'));
    }

}

查看

位于 \App\resources\views\public\company\index.blade.php

@extends('public.layout')

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

当我在我的控制器中取消注释 return $companies 时,我确实得到了结果,但是..我不确定为什么我的 - 非常简单的 - 视图没有呈现。谁能帮帮我?

检查是否设置了 $companies

@extends('public.layout')

@section('content')
    @if(isset($companies))
        Companies
        @foreach $companies as $company
            {{ $company->title }}
        @endforeach
    @else
        {{-- No companies to display message --}}
    @endif
@stop

错误指出编译 blade 文件时出现问题,可能是因为语法错误。 所以,只需将 foreach 变量包装在括号内,问题就应该得到解决。

@extends('public.layout')

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

这让我发疯。问题是我在 注释代码 中包含了如下内容:

// 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

我希望这对某人有所帮助。花了太多时间注释掉我所有的@foreach in code 才发现这是一个指令 in comments 导致了问题第一名.