繁体   English   中英

更改变量名时显示未定义的变量

[英]shows undefined variable when changing the variable name

在我的控制器页面中,我试图将所有数据从模式返回到视图。 我已将所有数据保存在变量中并传递到视图页面。 当我将变量名称保留为$post我收到错误:

Undefined variable: post (View: C:\xampp\htdocs\laravel\lsapp\resources\views\posts\index.blade.php)

控制器页面

// PostController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function index()
    {
        $post = Post::all();   
        return view('posts.index')-> with('posts', $post);
    }
    //remaining code blocks

查看页面代码

@extends('layouts.app')

@section('content')
<h1>this is index page.</h1>
@if(count($post) > 1)
    <h2>testing</h2>

@else
    <p>No Data</p>
@endif

@endsection

当我将变量名称更改为$ posts时,它可以正常工作。 为什么我必须保留与post第一个参数相同的变量名?

return view('posts.index')-> with('posts', $posts);  // it works fine

使用您传递的方法with('variableName', $variable')并在视图中使用$variableName变量

更换你的控制器

 return view('posts.index')-> with('posts', $posts);

并查看

@if(count($posts) > 1)

或者您可以更改控制器

 return view('posts.index')-> with('post', $posts);

并查看

@if(count($post) > 1)

当您发送变量以在此处查看$posts

return view('posts.index')->with('posts', $post);

在视图posts.index中使用@if(count($post) > 1)

如果您想在视图中使用$post作为变量,请将其发送为->with('post', $post);

如果你去

/vendor/laravel/framework/src/Illuminate/View/View.php

你会发现这种方法。 在此类中,您可以清楚地看到这些值与要渲染的视图相关联。

public function with($key, $value = null)
{
    if (is_array($key)) {
        $this->data = array_merge($this->data, $key);
    } else {
        $this->data[$key] = $value;
    }

    return $this;
}

如果你不想在这里使用它是另一种选择。

    return view('posts.index', compact('posts'));

暂无
暂无

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

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