刀片返回未定义的偏移量

问题描述 投票:4回答:3

我已经开始学习PHP Laravel了,我正在努力解决一些问题(可能非常简单)。当我渲染页面时,我看到以下错误:

BladeCompiler.php第584行中的ErrorException:未定义的偏移量: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时,我确实有结果,但是......我不确定为什么我的 - 非常简单 - 视图不呈现。谁能帮助我?

php laravel-5 blade
3个回答
5
投票

该错误指出在编译刀片文件时可能由于语法错误而出现问题。因此,只需将foreach变量包装在paranthesis中,就应该修复问题。

@extends('public.layout')

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

1
投票

检查$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

1
投票

这让我发疯了。问题是我在评论代码中加入了这样的代码:

// 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只是为了发现它是导致问题的评论中的指令。

© www.soinside.com 2019 - 2024. All rights reserved.