Laravel5.1 搭建简单的社区(九)--发表评论
首先创建一个评论控制器:CommentsController,并且添加resource路由:
php artisan make:controller CommentsController
Route::resource('comments', 'CommentsController');
在show.blade.php中展示发表评论界面:
<hr /> <!-- 判断用户是否登陆 --> @if(\Auth::check()) {!! Form::open(['method'=>'post','url'=>'/comments']) !!} <!-- 隐式传递discussion_id --> {!! Form::hidden('discussion_id',$discussion->id) !!} <!--- Body Field ---> <div class="form-group"> {!! Form::textarea('body', null, ['class' => 'form-control']) !!} </div> <!-- 提交 --> {!! Form::submit('发表评论',['class' => 'btn btn-primary form-control']) !!} {!! Form::close() !!} @else <a href="/user/login" class="btn btn-block btn-success">登录发表评论</a> @endif
接下来我们定义Request:
php artisan make:request StoreCommentsRequest
public function rules() { return [ // 评论内容非空 'body' => 'required', // discussion_id(隐式传递) 非空 'discussion_id' => 'required', ]; }
在CommentsController中保存数据:
public function store(Requests\StoreCommentsRequest $request) { // 将数据存入数据库 Comment::create(array_merge($request->all(), ['user_id' => \Auth::user()->id])); // 重定向 return redirect()->action('PostsController@show',['id' => $request->get('discussion_id')]); }