【问题标题】:LARAVEL - Pass variable from controller to viewLARAVEL - 将变量从控制器传递到视图
【发布时间】:2017-05-08 14:44:10
【问题描述】:

我想在主页上的表单下方显示我的帖子。 我已经可以将帖子添加到我的数据库了。

现在,如果我尝试在我的视图页面中使用这个变量,我只会得到未定义的变量。

路线 =

Route::resource('posts', 'PostController');

控制器 =

public function show()
{
    $posts = Post::orderBy('created_at', 'asc')->get();

    return view('/home', [
        'posts' => $posts
    ]);
}

查看

@if (count($posts) > 0)
    <div class="panel panel-default">
        <div class="panel-heading">
            Posts
        </div>

        <div class="panel-body">
            <table class="table table-striped task-table">

                <!-- Table Headings -->
                <thead>
                <th>Posts</th>
                <th>&nbsp;</th>
                </thead>

                <!-- Table Body -->
                <tbody>
                @foreach ($posts as $post)
                    <tr>
                        <!-- Post Name -->
                        <td class="table-text">
                            <div>{{ $post->description }}</div>
                        </td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>
    </div>
@endif

【问题讨论】:

  • 尝试在控制器中打印 $posts 以查看它显示的内容。同样在您看来,在循环之前添加一个 if 条件 if(isset($posts)) 。如果您需要更多帮助,请在此处发布您的视图代码
  • 显示访问变量的视图代码。
  • 你在哪里得到错误?在网页上?在日志文件中?
  • 在网页上。
  • 查看代码现已上线!

标签: php laravel


【解决方案1】:

正确的方法是仅将 Route::resources() 用于 REST(只是我的看法)。尝试创建一个新的路线,如

Route::get('hello-there', [
    'as' => 'front.index',
    'uses' => 'PostController@index',
]);

现在您可以通过以下方式访问您的操作:“www.mydomain.com/hell-there 下一步 - 如果是列表,则执行名为“index”的操作。

public function index()
{
    return view('home', [
        'posts' => Post::orderBy('created_at', 'asc')->get(),
    ])
}

你需要下面名为“home.blade.php”的目录下的刀片视图文件:

application_path/resources/

您的刀片文件看起来正确。祝你好运。

【讨论】:

  • 谢谢伙计,Route::resources() 是我想先做的方式,但这很好用。
【解决方案2】:

试试这个

public function show()
{
    $posts = Post::orderBy('created_at', 'asc')->get();

    return view('home', [
        'posts' => $posts
    ]);
}

并向我们展示您的刀片视图,路径和名称是什么?

【讨论】:

  • 向我们展示您的刀片视图,路径和名称是什么?
  • 大声笑,不喜欢,这是正确的答案,你的视图名称有问题
【解决方案3】:

你可以尝试使用:

return view('/home', compact('posts));

这对我有用。

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 2012-02-10
    • 2019-03-30
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多