本系列最終篇:引入 Eloquent 一對多關係(Page-Comment),實現前台評論發布、後台評論管理,並布置 Article 模組大作業。
php artisan make:model Comment -m
// database/migrations/xxxx_create_comments_table.php
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('nickname');
$table->string('email')->nullable();
$table->string('website')->nullable();
$table->text('content')->nullable();
$table->unsignedInteger('page_id');
$table->timestamps();
});
php artisan migrate
// Page.php
public function comments() {
return $this->hasMany(Comment::class, 'page_id', 'id');
}
// Comment.php
protected $fillable = ['nickname', 'email', 'website', 'content', 'page_id'];
php artisan make:controller CommentsController
// CommentsController.php
public function store() {
if (Comment::create(Input::all())) {
return Redirect::back();
}
return Redirect::back()->withInput()->withErrors('評論發表失敗!');
}
// routes.php
Route::post('comment/store', 'CommentsController@store');
@extends('_layouts.default')
@section('content')
... 文章內容 ...
<div id="comments">
@if (count($errors) > 0) ... @endif
<form action="{{ URL('comment/store') }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="page_id" value="{{ $page->id }}">
<input type="text" name="nickname" class="form-control" required>
<input type="email" name="email" class="form-control">
<input type="text" name="website" class="form-control">
<textarea name="content" id="newFormContent" class="form-control" rows="10" required></textarea>
<button type="submit" class="btn btn-success">提交</button>
</form>
@foreach ($page->comments as $comment)
<div class="comment">
<h4>{{ $comment->nickname }}</h4>
<p>{{ $comment->content }}</p>
</div>
@endforeach
</div>
@stop
php artisan make:controller Admin/CommentsController
// Admin/CommentsController.php
public function index() {
return view('admin.comments.index')->withComments(Comment::all());
}
public function edit($id) {
return view('admin.comments.edit')->withComment(Comment::find($id));
}
public function update(Request $request, $id) {
$this->validate($request, ['nickname' => 'required', 'content' => 'required']);
Comment::where('id', $id)->update(Input::except('_method', '_token'));
return Redirect::to('admin/comments');
}
public function destroy($id) {
Comment::find($id)->delete();
return Redirect::to('admin/comments');
}
// routes.php 後台群組內新增
Route::resource('comments', 'CommentsController');
admin/comments/index.blade.php:表格列表,含編輯/刪除按鈕admin/comments/edit.blade.php:編輯表單,預填數據參考 Pages 模組,完整實現:
- Article 模型、遷移(含 user_id、slug、published_at)
- 前台:文章列表、詳情頁、評論發布/顯示
- 後台:文章 CRUD、評論管理
- Eloquent 關係:User-Article 一對多、Article-Comment 一對多
- 路由:前台
articles/{id}、後台admin/articles、admin/comments共用
完成大作業即代表真正入門 Laravel 5!