Laravel Blade @foreach指令未定义的偏移量:1

时间:2018-04-24 16:56:16

标签: php laravel laravel-blade

我在尝试循环laravel分页项时遇到问题未定义索引。这是我的代码。

控制器

class SearchController extends Controller
{
    function index()
    {
        $term = request('q', '');

        $products = Product::where('name', 'LIKE', "%$term%")->paginate(12);

        $products->appends(['q' => $term]);

        $data['products'] = $products;

        // dd( $products );

        return view('products.search', $data);
    }
}

产品/ search.blade.php

@foreach( $products as $prod )

<div class="post">

    <a href="{{ route('product.show', ['name' => $prod->id]) }}">

        <p class="post-title">{{ $prod->name }}</p>

    </a>

</div>

@foreach

有错误

enter image description here

1 个答案:

答案 0 :(得分:1)

那是因为你最后有一个空的@foreach,你使用@endforeach关闭刀片中的foreach循环

@foreach( $products as $prod )

<div class="post">

    <a href="{{ route('product.show', ['name' => $prod->id]) }}">

        <p class="post-title">{{ $prod->name }}</p>

    </a>

</div>

@endforeach