Laravel 5 框架入门四完结篇

Page 和评论将使用 Eloquent 提供的“一对多关系”。最终,我们将得到一个个人博客系统的雏形,并布置一个大作业,供大家实战练习。

1. 初识 Eloquent

Laravel Eloquent ORM 是 Laravel 中非常重要的部分,也是 Laravel 能如此流行的原因之一。中文文档在:

1.

2.

在前面的教程中已经建立好的 learnlaravel5/app/Page.php 就是一个 Eloquent Model 类:

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

//

}

若想进一步了解 Eloquent,推荐阅读系列文章:深入理解 Laravel Eloquent

2. 创建 Comment 模型

首先我们要新建一张表来存储 Comment,命令行运行:

代码如下:

成功以后,修改 migration 文件 learnlaravel5/database/migrations/***_create_comments_table.php 的相应位置为:

increments('id'); $table->string('nickname'); $table->string('email')->nullable(); $table->string('website')->nullable(); $table->text('content')->nullable(); $table->integer('page_id'); $table->timestamps(); });

之后运行:

代码如下:

去数据库里瞧瞧,comments 表已经躺在那儿啦。

3. 建立“一对多关系”

修改 Page 模型:

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

public function hasManyComments()
{
return $this->hasMany('App\Comment','page_id','id');
}

}

搞定啦~ Eloquent 中模型间关系就是这么简单。

模型间关系中文文档:

4. 前台提交功能

修改 Comment 模型:

use Illuminate\Database\Eloquent\Model;

class Comment extends Model {

protected $fillable = ['nickname','email','website','content','page_id'];

}

增加一行路由:

代码如下:
);

运行以下命令创建 CommentsController 控制器:

代码如下:

修改 CommentsController:

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Redirect,Input;

use App\Comment;

class CommentsController extends Controller {

public function store()
{
if (Comment::create(Input::all())) {
return Redirect::back();
} else {
return Redirect::back()->withInput()->withErrors('评论发表失败!');
}

}

}

修改视图 learnlaravel5/resources/views/pages/show.blade.php:

{{ $page->body }}

@if (count($errors) > 0)
<div class="alert alert-danger">

Whoops!

There were some problems with your input.

    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif

<div id="new">
<form action="{{ URL('comment/store') }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="page_id" value="{{ $page->id }}">
<div class="form-group">

Email address
Home page
Content