Menu

91.更新话题(一)

本节说明

  • 对应视频教程第 91 小节:A Thread Can Be Updated

本节内容

下面我们进行话题更新功能的开发。我们设定只有话题的创建者才能更新允许更新,且只能更新titlebody字段,并且更新的内容要符合我们设定的验证规则。因为,我们来添加 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;
    }
    .
    .

运行测试:
file

本文章首发在 Laravel China 社区
上一篇 下一篇
讨论数量: 0
发起讨论


暂无话题~