首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel 5请求更改数据

Laravel 5请求更改数据
EN

Stack Overflow用户
提问于 2015-02-19 07:34:11
回答 1查看 4.2K关注 0票数 6

我遇到了一个需要修改需要验证的数据的实例,即当未提交任何段塞时,从标题中创建一个,然后验证它是唯一的。

请求有一个方法replace(),它应该替换请求上的输入数据,但它似乎不起作用。有人能在这上面发光吗?这就是我所拥有的:

代码语言:javascript
复制
<?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(),

        ];
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-19 17:55:51

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

例如:

代码语言:javascript
复制
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 (我还在使用这个版本),很奇怪它被删除了。

当您将上述方法更改为:

代码语言:javascript
复制
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班都放在这里了。我发送空数据,并且由于修改后的all()方法,即使是空数据,验证也会通过,因为我手动地将这些数据设置为验证。如果删除此all()方法并发送空数据,当然会显示错误。

代码语言:javascript
复制
<?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;
    }

}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28600823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档