繁体   English   中英

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

[英]Laravel: Undefined variable in blade view

这是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

为什么会出现以下错误?

ErrorException in 408148d5409ae6eebf768dc5721bd0d1d9af48af.php 第 9 行:未定义变量:图像(视图:/Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)

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

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

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

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

尝试像这样传递数据。

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

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

你的代码应该是这样的

public function admin() {
    $images = Image::paginate();

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

}

为什么使用[ '$images' => $images] 那就是问题所在。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM