【问题标题】:In Laravel "Undefined offset: 0"在 Laravel “未定义的偏移量:0”
【发布时间】:2020-01-02 16:52:34
【问题描述】:

在 Laravel 视图中未定义的偏移量:0

我之前说有问题

在参数 1 中期望数组,但给定对象

并通过->toArray 修复它。然后就出现了这个问题

public function index()
    {
        $products = Product::paginate(3)->toArray();

        return view ('inventory.layout', [
            'products' => $products
        ]);
    }

这是在视图文件中显示我的产品 我试过用['data']字符串替换0键但是没用。

  @if (isset($products)) 
        @if ($arrkeys = array_keys($products[0])) 
            @foreach ($arrkeys as $key)  
                <th>{{$key}}</th>
            @endforeach
        @endif 
   @endif

【问题讨论】:

  • 在控制器中,在返回视图之前,使用 dd($products); 转储 $products 的内容,然后查看函数调用实际返回的内容。
  • 我已经这样做了并向我展示了一个三分页数组,但是当我想在视图中显示它时,显示此错误“未定义偏移量:0”
  • 您能否向我们展示响应结构,以便我们将其与您在视图中编写的代码进行比较,并检查可能是什么问题
  • 确定:array:12 [▼ "current_page" => 1 "data" => array:3 [▼ 0 => array:29 [▶] 1 => array:29 [▶] 2 => array:29 [▶] ] "first_page_url" => "localhost:8080/Import-CSV-Laravel/public/layout?page=1" "from" => 1 "last_page" => 10 "last_page_url" => "localhost:8080/Import-CSV-Laravel/public/layout?page=10" "next_page_url" => "localhost:8080/Import-CSV-Laravel/public/layout?page=2 " "path" => "localhost:8080/Import-CSV-Laravel/public/layout" "per_page" => 3 "prev_page_url" => null "to" => 3 "total" => 30 ]
  • array:12 [▼ "current_page" => 1 "data" => array:3 [▼ 0 => array:29 [▶] 1 => array:29 [▶] 2 =>数组:29 [▶] ]

标签: laravel pagination


【解决方案1】:

如果你需要显示分页使用这样的代码

public function index()
    {
        $products = Product::paginate(3);

        return view ('inventory.layout', [
            'products' => $products
        ]);
    }



And this is to show my products in view file
I've tried to replace the 0 key with ['data'] string but useless.



  @if (isset($products)) 
           @foreach ($products as $key)  
                <th>{{$key}}</th>
            @endforeach
    //for pagination
    <div>{{$products->links()}}</div>
  @endif

【讨论】:

    【解决方案2】:

    如果你想显示数组的,试试这个:

      @if (isset($products))
          @foreach ($products as $key => $value)  
                <th>{{$key}}</th>
          @endforeach
      @endif
    

    但如果你想显示

      @if (isset($products))
          @foreach ($products as $key => $value)  
                <th>{{$value}}</th>
          @endforeach
      @endif
    

    【讨论】:

      猜你喜欢
      • 2014-06-25
      • 2015-12-20
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2019-03-21
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多