91.更新话题(一)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 91 小节:A Thread Can Be Updated
本节内容
下面我们进行话题更新功能的开发。我们设定只有话题的创建者才能更新允许更新,且只能更新title
和body
字段,并且更新的内容要符合我们设定的验证规则。因为,我们来添加 3 个测试:
forum\tests\Feature\UpdateThreadsTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class UpdateThreadsTest extends TestCase
{
use RefreshDatabase;
public function setUp()
{
parent::setUp();
// 每个测试都需要用到以下操作
$this->withExceptionHandling();
$this->signIn();
}
/** @test */
public function unauthorized_users_may_not_update_threads() // 只有话题创建者才能更新
{
$thread = create('App\Thread',['user_id' => create('App\User')->id]);
$this->patch($thread->path(),[])->assertStatus(403);
}
/** @test */
public function a_thread_requires_a_title_and_body_to_be_updated() // 更新的字段要符合规则
{
$thread = create('App\Thread',['user_id' => auth()->id()]);
$this->patch($thread->path(),[
'title' => 'Changed.'
])->assertSessionHasErrors('body');
$this->patch($thread->path(),[
'body' => 'Changed.'
])->assertSessionHasErrors('title');
}
/** @test */
public function a_thread_can_be_updated_by_its_creator() // 话题可以成功更新
{
$thread = create('App\Thread',['user_id' => auth()->id()]);
$this->patch($thread->path(),[
'title' => 'Changed.',
'body' => 'Changed body.'
]);
tap($thread->fresh(),function ($thread) {
$this->assertEquals('Changed.',$thread->title);
$this->assertEquals('Changed body.',$thread->body);
});
}
}
添加更新路由:
forum\routes\web.php
.
Route::get('threads/{channel}/{thread}','ThreadsController@show');
Route::patch('threads/{channel}/{thread}','ThreadsController@update');
.
修改控制器:
forum\app\Http\Controllers\ThreadsController.php
.
.
public function update($channelId,Thread $thread)
{
// 应用授权策略
$this->authorize('update',$thread);
// 验证规则
$thread->update(request()->validate([
'title' => 'required|spamfree',
'body' => 'required|spamfree'
]));
return $thread;
}
.
.
运行测试: