[英]LARAVEL - Pass variable from controller to view
I want to show my posts on the homepage just under my form. 我想在主页上的表格下方显示我的帖子。 I can already add post to my DB. 我已经可以将帖子添加到我的数据库了。
Now I just get Undefined variable if I try to use this variable in my view page. 现在,如果尝试在视图页面中使用此变量,我将得到未定义的变量。
Route = 路线=
Route::resource('posts', 'PostController');
Controller = 控制器=
public function show()
{
$posts = Post::orderBy('created_at', 'asc')->get();
return view('/home', [
'posts' => $posts
]);
}
View 视图
@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> </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
The right way is using Route::resources() only for REST (just my opinion). 正确的方法是仅将Route :: resources()用于REST(这只是我的看法)。 Try to create a new Route like 尝试创建一条新的路线,例如
Route::get('hello-there', [
'as' => 'front.index',
'uses' => 'PostController@index',
]);
Now u can get access to your action by: "wwww.mydomain.com/hell-there Next step - make action named "index" if it is list. 现在,您可以通过以下方式访问您的操作:“ wwww.mydomain.com/hell-there下一步-如果该操作是列表,则将其命名为” index”。
public function index()
{
return view('home', [
'posts' => Post::orderBy('created_at', 'asc')->get(),
])
}
U need blade view file in below directory named "home.blade.php": 您需要在名为“ home.blade.php”的目录下的刀片视图文件:
application_path/resources/
Your blade file looks correct. 您的刀片文件看起来正确。 Good luck mate. 祝你好运。
Try this 尝试这个
public function show()
{
$posts = Post::orderBy('created_at', 'asc')->get();
return view('home', [
'posts' => $posts
]);
}
and show us your blade view, what the path and name? 并向我们显示您的刀片视图,路径和名称是什么?
you could try to use: 您可以尝试使用:
return view('/home', compact('posts)); 返回视图('/ home',compact('posts));
this works for me. 这对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.