建立 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)
public function up() { Schema::create('post_comments', function (Blueprint $table) { $table->increments('id'); $table->integer('post_id')->unsigned(); $table->text('content'); $table->timestamps(); }); }執行 migrate 建立資料表 (artisan command)
php artisan migrate修改 PostComment model (app/PostComment.php)
class PostComment extends Model { protected $fillable = ['content']; }修改 Post model (app/Post.php)
use App\PostComment; ... public function comments() { return $this->hasMany(PostComment::class); }新增留言的 view (resources/views/post/show.blade.php)
<div class="comment"> <div class="comment-add"> {!! Form::open(['route' => ['post.comment.store', $post->id]]) !!} <div class="form-group"> {!! Form::label('content', '新增留言') !!} {!! Form::textarea('content', null, ['class' => 'form-control']) !!} </div> <div class="form-group"> {!! Form::submit(null, ['class' => 'btn btn-primary btn-lg btn-block']) !!} </div> {!! Form::close() !!} </div> </div>新增留言的 store (app/Http/Controllers/PostCommentController.php)
public function store(Post $post, Request $request) { $post->comments()->create($request->all()); return redirect()->route('post.show', $post->id); }顯示留言的 view (resources/views/post/show.blade.php)
@foreach($post->comments as $index => $comment) <hr> <div class="comment-list"> <div class="clearfix"> #{{ $index + 1 }} <form class="pull-right" action="{{ route('post.comment.destroy', [$post->id, $comment->id]) }}" method="POST"> {{ csrf_field() }} {{ method_field('DELETE') }} <input class="btn btn-danger" type="submit" name="submit" value="刪除"> </form> <a class="pull-right btn btn-primary" href="{{ route('post.comment.edit', [$post->id, $comment->id]) }}">編輯</a> </div> <p> {{ $comment->content }} </p> <div class="text-right"> {{ $comment->created_at }} </div> </div> @endforeach刪除 (app/Http/Controllers/PostCommentController.php)
public function destroy(Post $post, PostComment $comment) { $comment->delete(); return redirect()->route('post.show', $post->id); }編輯自己寫!
留言
張貼留言