【问题标题】:Laravel form request not updating nullable fieldLaravel 表单请求不更新可空字段
【发布时间】:2020-04-19 04:24:54
【问题描述】:

我在 Laravel 中创建了一个 PostRequest(使用 php artisan make:request PostRequest)。我有三列:标题、内容和标签)。标签列可以为空。当我添加一些帖子时没有问题,我可以添加标题、内容和标签。

但是,当我想编辑帖子时,标题和内容列会发生变化,但标签列不会。怎么办?

控制器

public function update(PostRequest $request, Post $post)
{
    $validated = $request->validated();

    Post::whereId($post->id)->update($validated);

    return redirect('/posts')->with('success', 'success');
}

PostRequest.php

public function rules()
{
    switch ($this->method()) {
        case 'POST':
        {
            return [
                'title' => 'required|max:512',
                'content' => 'required',
            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [
                'title' => 'required|max:512',
                'content' => 'required',
            ];
        }
        default:
            break;
    }
}

Post.php(模型)

protected $fillable = [
    'title',
    'content',
    'tag',
    'created_at',
];

【问题讨论】:

  • 表单请求只返回您定义的字段。如果您希望 tag 返回,请在您的 PostRequest 中创建验证规则

标签: php laravel laravel-6 laravel-validation


【解决方案1】:

您正在使用 $request->validated() 过滤您的请求输入并仅返回经过验证的字段。因此,为 tag 添加新规则将解决您的问题:

return [
    'title' => 'required|max:512',
    'content' => 'required',
    'tag' => 'nullable'
];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-20
    • 2018-12-25
    • 2018-03-15
    • 2019-11-11
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多