Laravel 5请求 - 更改数据

Luk*_*den 5 request laravel laravel-5 laravel-validation laravel-request

我遇到了一个需要更改需要验证的数据的实例,即当没有提交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(),

        ];
    }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*łek 5

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

例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑

这个方法是在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;
}
Run Code Online (Sandbox Code Playgroud)

EDIT2

我把整个工人阶级都放在这里TestRequest.我发送空数据,因为修改后的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;
    }

}
Run Code Online (Sandbox Code Playgroud)