Laravel:刀片视图中的未定义变量

新手上路,请多包涵

这是 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 在我的控制器中明确定义。

原文由 Sahand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 238
2 个回答

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

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

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

原文由 Joe 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试像这样传递数据。

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

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

原文由 Rehan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题