公司導入 Laravel 分享 - 13. 進階實作 - 文章留言

建立 Route (routes/web.php)
Route::resource('post.comment', 'PostCommentController');
建立 Model、Controller 和 Migration (artisan command)
php artisan make:model PostComment -m -r
撰寫資料庫 schema (database/migrations/2017_05_09_064131_create_post_comments_table.php)
  1. public function up()
  2. {
  3. Schema::create('post_comments', function (Blueprint $table) {
  4. $table->increments('id');
  5. $table->integer('post_id')->unsigned();
  6. $table->text('content');
  7. $table->timestamps();
  8. });
  9. }
執行 migrate 建立資料表 (artisan command)
php artisan migrate
修改 PostComment model (app/PostComment.php)
  1. class PostComment extends Model
  2. {
  3. protected $fillable = ['content'];
  4. }
修改 Post model (app/Post.php)
  1. use App\PostComment;
  2. ...
  3. public function comments()
  4. {
  5. return $this->hasMany(PostComment::class);
  6. }
新增留言的 view (resources/views/post/show.blade.php)
  1. <div class="comment">
  2. <div class="comment-add">
  3. {!! Form::open(['route' => ['post.comment.store', $post->id]]) !!}
  4. <div class="form-group">
  5. {!! Form::label('content', '新增留言') !!}
  6. {!! Form::textarea('content', null, ['class' => 'form-control']) !!}
  7. </div>
  8. <div class="form-group">
  9. {!! Form::submit(null, ['class' => 'btn btn-primary btn-lg btn-block']) !!}
  10. </div>
  11. {!! Form::close() !!}
  12. </div>
  13. </div>
新增留言的 store (app/Http/Controllers/PostCommentController.php)
  1. public function store(Post $post, Request $request)
  2. {
  3. $post->comments()->create($request->all());
  4.  
  5. return redirect()->route('post.show', $post->id);
  6. }
顯示留言的 view (resources/views/post/show.blade.php)
  1. @foreach($post->comments as $index => $comment)
  2. <hr>
  3. <div class="comment-list">
  4. <div class="clearfix">
  5. #{{ $index + 1 }}
  6. <form class="pull-right" action="{{ route('post.comment.destroy', [$post->id, $comment->id]) }}" method="POST">
  7. {{ csrf_field() }}
  8. {{ method_field('DELETE') }}
  9. <input class="btn btn-danger" type="submit" name="submit" value="刪除">
  10. </form>
  11. <a class="pull-right btn btn-primary" href="{{ route('post.comment.edit', [$post->id, $comment->id]) }}">編輯</a>
  12. </div>
  13. <p>
  14. {{ $comment->content }}
  15. </p>
  16. <div class="text-right">
  17. {{ $comment->created_at }}
  18. </div>
  19. </div>
  20. @endforeach
刪除 (app/Http/Controllers/PostCommentController.php)
  1. public function destroy(Post $post, PostComment $comment)
  2. {
  3. $comment->delete();
  4.  
  5. return redirect()->route('post.show', $post->id);
  6. }
編輯自己寫!

留言