php - 未定义变量:posts(查看:C:\xampp\htdocs\practiseapp\resources\views\dashboard.blade.php)
问题描述
我是 laravel 的新手,我只是创建一个简单的应用程序,用户可以在其中登录和注册,然后在登录后在仪表板中写帖子,我试图在保存在数据库中的仪表板中显示用户发布数据,但是我收到此错误:
未定义变量:posts(查看:C:\xampp\htdocs\practiseapp\resources\views\dashboard.blade.php)
我想我已经定义了帖子,我不知道出了什么问题,任何帮助将不胜感激谢谢....
我的仪表板:
@extends('layout.master')
@section('content')
<div class="col-sm-6 col-sm-offset-3">
<header><h3>What do you wanna say</h3></header>
<form method="post" action="{{route('post.create')}}">
{{csrf_field()}}
<div class="panel-body">
<div class="form-group">
<textarea class="form-control" name="body" id="body" rows="5" placeholder="Enter your post">
</textarea>
</div>
<button type="submit" class="btn btn-primary">Create post</button>
</form>
</div>
</div>
<section class="row-posts">
<div class="col-md-6 col-sm-offset-3">
<header><h3>Other people posts</h3></header>
@foreach($posts as $post)
<article class="post">
<p>{{ $post->body }}</p>
<div class="info">
posted by {{ $post->user->name}} on {{$post->created_at}}
</div>
<div class="interaction">
<a href="#">Like</a>|
<a href="#">Disike</a>|
<a href="#">Edit</a>|
<a href="#">Delete</a>
</div>
</article>
@endforeach
</div>
</section>
@endsection
PostController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Post;
use App\UserTypes;
use Auth;
use Hashids;
use Redirect;
use Illuminate\Http\Request;
use Hash;
class PostController extends Controller
{
public function show()
{
//Fetching all the posts from the database
$posts = Post::all();
return view('dashboard',['posts'=> $posts]);
}
public function store(Request $request)
{
$this->validate($request,[
'body' => 'required'
]);
$post = new Post;
$post->body = $request->body;
$request->user()->posts()->save($post);
return redirect()->route('dashboard');
}
}
解决方案
我认为您非常接近,但我有一些想法可能对您有所帮助。
首先,您是否检查过您的路线是否设置正确routes/web.php
?如果你使用了 Laravel 文档中的一些示例,那么你的路由可能会在没有使用你编写的控制器的情况下返回视图。如果你有这样的东西:
Route::get('/', function () {
return view('dashboard');
});
...那么您可能希望将其替换为以下内容:
Route::get( '/', 'PostController@show );
有许多不同的方式来管理你的路由——Laravel 文档会很好地解释其中的一些。
此外,当将内容从控制器传递到视图时,我喜欢将我的对象分配给关联数组,然后在使用视图方法时传递该数组。这完全是个人喜好,但您可能会发现它很有用。有点像这样:
public function show()
{
// Create output array - store things in here...
$output = [];
$output[ "posts" ] = Post::all();
// Render the Dashboard view with data...
return view( 'dashboard', $output );
}
希望有些帮助!
推荐阅读
- python - 如何在列表理解中执行多项操作
- assembly - 启用分页后的指令似乎没有执行
- puppet - How to download puppet manifest file from master using agent?
- javascript - 如何在 php html css js 中创建网格视图/列表视图?
- c# - Google People Api 联系人已创建,但我在任何地方都看不到它
- go - 如何检查两个结构是否相等
- c# - 在 ASP.NET Core MVC 中保留下拉值
- javascript - 在打字稿(javascript)中向类方法添加方法
- java - ElasticSearch - 模糊搜索 java api 结果不正确
- python - 在 CloudML 中的 Tensorflow 中读取 pandas pickle 文件