Justin's Words

Laravel CRUD

本文讲 Laravel CRUD(create, read, update, delete),学习 Laravel CRUD 期间受 scotch.io 帮助很大,跳转过去看效果可能更好。

News Table

创建迁移文件

直接通过 artisan migrate:make 创建迁移文件即可:

1
php artisan migrate:make create_news_table

app/database/migrations 下找到刚刚创建的迁移文件,我的是 2014_11_30_084437_create_news_table.php,填写表创建条件,查看官方教程,以下是我的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateNewsTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('news', function($table) {
$table->increments('id');
$table->string('title');
$table->longText('content');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('news');
}

}

数据填充 seed

Laravelapp/seeds 下默认有一个 DatabaseSeeds.php,直接在里面操作好了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class DatabaseSeeder extends Seeder {
public function run()
{
Eloquent::unguard();
$this->call('NewsTableSeeder');
$this->command->info('News table seeded');
}
}

class NewsTableSeeder extends Seeder
{
public function run()
{
News::create(
array(
'author' => 'Jackie',
'title' => 'Fly like a butterfly',
'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum doloribus maxime necessitatibus ratione nesciunt perferendis quisquam, molestiae illum. Eos suscipit illum, quod expedita dolorem facere inventore consequatur sit harum quam.',
),
array(
'author' => 'Jackie',
'title' => 'Fly like a butterfly',
'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum doloribus maxime necessitatibus ratione nesciunt perferendis quisquam, molestiae illum. Eos suscipit illum, quod expedita dolorem facere inventore consequatur sit harum quam.',
)
);
}
}

多创建几个都行,官方教程在这

然后通过 Artisan Cli 进行数据填充即可:

1
php artisan db:seed

Route::resource()

你希望给 news 路由以 CRUD 操作,Laravel 已经帮你实现了一个控制器,在 app/routes.php 添加:

1
Route::resource('news', 'NewsController');

这样路由设置就完成了。

News Model

创建一个 News Model 是最好的,这样你就省得去用 DB 来查询数据了。 在 app/models 创建 News.php

1
2
3
4
5
6
<?php
class News extends Eloquent {

protected $table = 'news';

}

就是这么简单,继承 Eloquent 类。

CRUD Controller

利用 artisan 创建一个 CRUD Controlelr:

1
php artisan controller:make NewsController

你就可以在 app/controllers 看到 NewsControlelr.php。 或者手动创建 app/controllers/NewsController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php

class NewsController extends \BaseController {

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
}

/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}

/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}

/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}

/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}

}

CRUD 路由结构

HTTP Verb Path (URL) Action (Method) Route Name
GET /news index news.index
GET /news/create create news.create
POST /news store news.store
GET /news/{id} show news.show
GET /news/{id}/edit edit news.edit
PUT/PATCH /news/{id} update news.update
DELETE /news/{id} destroy news.destroy

index()

index() 负责展示 news 首页,比如这样:

1
2
3
4
public function index()
{
return View::make('pages.news.index');
}

create()

create() 负责展示创建新的新闻的页面,比如:

1
2
3
4
public function create()
{
return View::make('pages.news.create');
}

store()

store() 负责保存从 create() POST 过来的数据,路由是 /news,以下代码适用于 Ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public function store()
{
$inputs = Input::all();

$rules = array(
'title' => 'required',
'content' => 'required',
);
$messages = array(
'title.required' => '1',
'content.required' => '1',
);

$validator = Validator::make($inputs, $rules, $messages);

if ($validator->passes()) {
$news = new News();
$news->title = htmlspecialchars(trim($inputs['title']));
$news->content = htmlspecialchars(trim($inputs['content']));
$news->save();
// 发布成功,返回 {'success': '1'} 供 Ajax 处理
return json_encode(array('success' => '1'));
} else {
// 发布失败,返回特定 json 供 Ajax 处理
return $validator->messages()->toJson();
}
}

show($id)

show() 负责展示新闻,路由是 news/{id},比如:

1
2
3
4
5
public function show($id)
{
$news = News::find($id);
return View::make('pages.news.show')->with('news', $news);
}

然后你可以在 pages/news/show.blade.php 注入数据:

1
2
3
<p>{{ $news->id }}</p>
<p>{{ $news->title }}</p>
<p>{{ $news->content }}</p>

edit($id)

edit($id) 是用来展示新闻修改页面,路由是 news/{id}/edit,例子:

1
2
3
4
5
public function edit($id)
{
$news = News::find($id);
return View::make('pages.news.edit')->with('news', $news);
}

其实这个和 show($id) 的不同就是路由和前端页面,前端我就不写在这里了,有疑惑可以去 scotch.io 学习。

update($id)

update($id) 接受 PUT 过来的新数据然后进行更新,路由是 news/{id},例子适用于 Ajax:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public function update($id)
{
$inputs = Input::all();

$rules = array(
'title' => 'required',
'content' => 'required',
);

$messages = array(
'title.required' => '1',
'content.required' => '1',
);

$validator = Validator::make($inputs, $rules, $messages);

if ($validator->passes()) {
$news = News::find($id);
$news->title = htmlspecialchars(trim($inputs['title']));
$news->content = htmlspecialchars(trim($inputs['content']));
$news->save();
return json_encode(array('success' => '1'));
} else {
return $validator->messages()->toJson();
}
}

destroy($id)

destroy($id) 负责接受 DELETE 方法删除数据,路由是 /news/{id},例子使用 Ajax:

1
2
3
4
5
6
7
public function destroy($id)
{
$news = News::find($id);
$news->delete();

return json_encode(array('success' => '1'));
}