我是Laravel的新手保存在数据库中的仪表板中的数据,但我遇到了此错误:
未定义的变量:帖子(查看:c: xampp htdocs ractiSeApp resources views view dashboard.blade.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 AppHttpControllers;
use AppHttpRequests;
use AppPost;
use AppUserTypes;
use Auth;
use Hashids;
use Redirect;
use IlluminateHttpRequest;
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 );
}
希望其中一些会有所帮助!
尝试以下代码,
<?php
namespace AppHttpControllers;
use AppHttpRequests;
use AppPost;
use AppUserTypes;
use Auth;
use Hashids;
use Redirect;
use IlluminateHttpRequest;
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');
}
}