【问题标题】:Laravel: Undefined variable in blade viewLaravel:刀片视图中的未定义变量
【发布时间】:2017-08-24 00:05:55
【问题描述】:

这是AdminController.php

<?php

namespace App\Http\Controllers;

use Response;

use Illuminate\Support\Facades\DB;
use App\Caption;
use App\Image;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function admin() {
        $images = Image::paginate();

        return view('admin',[ '$images' => $images]);
    }
}

这是admin.blade.php:

@extends('template')

@section('title')
    Admin Page
@endsection

@section('header')
@endsection

@section('main')
    @if (Auth::check())
        @foreach ($images as $image)
            <p value='{{$image->id}}'>{{$image->content}}</p>
            <form action="image/{{$image->id}}/delete" method="post">
                <button type="submit">Delete caption</button>
            </form> 
            <form action="image/{{$image->id}}/approve" method="post">
                <button type="submit">Accept image</button>
            </form>
        @endforeach
    @else
        <p>Login first</p>
    @endif
@endsection

@section('footer')
@endsection

为什么会出现以下错误?

408148d5409ae6eebf768dc5721bd0d1d9af48af.php 第 9 行中的错误异常: 未定义变量:图像(查看:/Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)

$images在我的控制器中明确定义。

【问题讨论】:

  • 试试这个return view('admin',compact('images'));
  • Image::paginate() 是你写的范围吗?因为通常你会做这样的事情:$images = Image::all()-&gt;paginate(15);
  • 更正码应该是:return view('admin',[ 'images' =&gt; $images]);

标签: php html laravel view laravel-blade


【解决方案1】:

在将数据传递给视图时,您使用了$images 作为变量名。这会导致刀片创建一个名为 $$images 的变量。

return view('admin',[ 'images' => $images]);

将导致视图创建一个名为$images的变量

【讨论】:

  • 太好了,我浪费了 4 个小时终于找到你了
【解决方案2】:

尝试像这样传递数据。

$images = Image::paginate();
return view("admin")->with('images',$images);

基本上,你不需要在变量名中使用$

【讨论】:

    【解决方案3】:

    你的代码应该是这样的

    public function admin() {
        $images = Image::paginate();
    
        return view('admin',[ 'images' => $images]);
    

    }

    为什么你使用[ '$images' =&gt; $images]。这就是问题所在。

    【讨论】:

      【解决方案4】:

      您也可以使用此方法将您的数据传递给查看

       return view('admin',compact('images'));
      

      【讨论】:

        猜你喜欢
        • 2014-03-15
        • 2017-02-08
        • 2018-07-24
        • 2017-06-17
        • 2018-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-08
        相关资源
        最近更新 更多