这是我的控制器名为CommentController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use Auth;
class CommentsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view('comments.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$comment= new Comment();
$comment->user_id=Auth::user()->id;
$comment->body=$request->body;
$comment->save();
return back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show()
{
//
$comments=comment::all();
return view('comments',['comments'=>$comments]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
这是我的布局代码,名为create.blade.html
<html>
<head>
<h1>DONE</h1>
</head>
<body>
<div class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Comments</h3></header>
<form action="/comments" method="post">
{{csrf_field()}}
<div class="form-group">
<textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your review on above game"></textarea>
</div>
<button type="submit" class="btn btn-primary">Post Comment</button>
</form>
</div>
</div>
<?php foreach($comments as $comment) ?>
<h1><?php echo $comment ?> <h1>
</body>
</html>
这是我的路线代码,名为web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::resource('comments','CommentsController');
Route::get('comments.create','CommentsController@show');
?>
现在,无论我提交的数据是在数据库中输入的,但是当我尝试显示该数据时,它会给我错误未定义的变量:注释。在此先感谢:-)
答案 0 :(得分:1)
那是因为您没有从$comments
方法传递create()
变量,该变量看起来像这样:
public function create()
{
$comments = comment::all();
return view('comments.create', ['comments' => $comments]);
}
同时删除Route::get('comments.create'
,因为尝试覆盖资源路由是个坏主意。使用create()
显示表单,使用show()
显示一条评论。