首先建立一個評論控制器:CommentsController,而且添加resource路由:php
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:post
php artisan make:request StoreCommentsRequest
public function rules() { return [ // 評論內容非空 'body' => 'required', // discussion_id(隱式傳遞) 非空 'discussion_id' => 'required', ]; }
在CommentsController中保存數據:ui
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')]); }