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

问题描述 投票:0回答:3

在我的控制器页面中,我尝试将所有数据从模式返回到视图。我将所有数据保存在一个变量中并传递到视图页面。当我将变量名称保留为

$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 时,它工作正常。为什么我必须与 posts 第一个参数保持相同的变量名称?

return view('posts.index')-> with('posts', $posts);  // it works fine
php laravel laravel-blade
3个回答
5
投票

因为在 with 方法中你传递了

with('variableName', $variable')
并且在 view 中你可以使用
$variableName
变量

更换控制器

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

并查看

@if(count($posts) > 1)

或者您可以更换控制器

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

并查看

@if(count($post) > 1)

4
投票

当您发送变量以在此处查看时:


$posts

在您的视图中使用 
return view('posts.index')->with('posts', $post);

posts.index
如果您想使用

@if(count($post) > 1)

作为视图中的变量,请将其发送为

$post
    


3
投票

/供应商/laravel/framework/src/Illuminate/View/View.php

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

->with('post', $post);

如果您不想使用此功能,这里有一个替代方案。

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

© www.soinside.com 2019 - 2024. All rights reserved.