Laravel 5 请求 - 更改数据

Laravel 5 Request - altering data

我遇到过一个实例,我需要更改需要验证的数据,即当没有提交 slug 时,从标题创建一个然后验证它是唯一的。

该请求有一个方法 replace(),该方法本应替换请求中的输入数据,但它似乎不起作用。任何人都可以照亮这个吗?这是我的:

<?php namespace Purposemedia\Pages\Http\Requests;

use Dashboard\Http\Requests\Request;
use Illuminate\Auth\Guard;

class PageRequest extends Request {

    /**
     * [authorize description]
     * @return {[type]} [description]
     */
    public function authorize( Guard $auth) {
        return true;
    }

    /**
     * [rules description]
     * @return {[type]} [description]
     */
    public function rules() {
        // Get all data from request
        $data = $this->request->all();
        if( $data['slug'] === '' ) {
            // if the slug is blank, create one from title data
            $data['slug'] = str_slug( $data['title'], '-' );
            // replace the request data with new data to validate
            $this->request->replace( $data );
        }
        return [

            'title' => 'required|min:5|max:255',
            'slug' => 'min:5|max:255|alpha_dash|unique:pages,slug' . $this->getSegmentFromEnd(),

        ];
    }

}

你应该用 formatInput 方法来做。您在此方法中 return 的数据将用于验证器检查:

例如:

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;
}

编辑

这个方法是在Laravel 2个月前的(我还在用这个版本),很奇怪它被删除了。

将上述方法改为:

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

我把整个工作放在这里 TestRequest class。我发送了空数据,并且由于修改了 all() 方法,即使数据为空,验证也通过了,因为我手动将这些数据设置为验证。如果我删除此 all() 方法并发送空数据,我当然会显示错误

<?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;
    }

}