我是laravel的新手,我只是在创建一个简单的应用程序,用户可以登录和注册,登录后在仪表板中写入帖子,然后尝试在仪表板中显示用户发布的数据,该数据保存在数据库中,但出现此错误:
未定义的变量:帖子(视图: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');
}
}
答案 0 :(得分:1)
我认为您已经很接近了,但是我有一些想法可能会对您有所帮助。
首先,您是否检查过routes/web.php
中的路由设置正确?如果您使用了Laravel文档中的一些示例,则可能是您的路线返回了视图而未使用您编写的Controller。如果您有类似这样的内容:
Route::get('/', function () {
return view('dashboard');
});
...那么您可能想要将其替换为以下内容:
Route::get( '/', 'PostController@show );
管理路由的方法有很多-Laravel Docs可以很好地解释其中的一些问题。
此外,当将内容从Controller传递到View时,我喜欢将对象分配给关联数组,然后在使用view方法时将该数组传递给该数组。这完全是个人喜好,但您可能会发现它很有用。像这样的东西:
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 );
}
希望其中一些帮助!
答案 1 :(得分:0)
尝试以下代码,
<?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::get();
return view('dashboard', compact('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');
}
}