Laravel 5 Request - altering data

我是研究僧i 提交于 2019-12-05 11:25:20
Marcin Nabiałek

You should do it in formatInput method. Data you return in this method will be used for validator to check:

For example:

protected function formatInput()
{
    $data = $this->all();
    if( $data['slug'] === '') {
        // if the slug is blank, create one from title data
        $data['slug'] = str_slug( $data['title'], '-' );
    }

    return $data;
}

EDIT

This method was in Laravel 2 months ago (I'm still using this version), that's quite strange it was removed.

The same effect you should receive when you change above method into:

public function all()
{
    $data = parent::all();
    if( $data['slug'] === '') {
        // if the slug is blank, create one from title data
        $data['slug'] = str_slug( $data['title'], '-' );
    }

    return $data;
}

EDIT2

I put here the whole working TestRequest class. I send empty data and because of modified all() method even if empty data, validation passes because I manually set those data to validate. If I remove this all() method and send empty data of course I will get errors displayed

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class TestRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'title' => 'required|min:2|max:255',
            'slug' => 'min:2|max:255'
        ];
    }

    public function response(array $errors){
        dd($errors);
    }

    public function all(){
        $data = parent::all();
        $data['title'] = 'abcde';
        $data['slug'] = 'abcde';
        return $data;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!