Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5.4 modify data before validation in request [closed]

I have my custom Request, which extends the Backpack CrudController.

Now I would like to override the prepareForValidation of the ValidatesWhenResolvedTrait since it looks like the right place to modify my incoming data, but I can't figure out how ...

So my first question is, can I override this method? Its protected ...

protected function prepareForValidation()

And my second question, how can I modify my input on the Request or FormRreuqest objects?

Here is my RequestClass

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Config;

class DonationsRequest extends \Backpack\CRUD\app\Http\Requests\CrudRequest
{


    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // only allow updates if the user is logged in
        return \Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:255',
            'email' => 'required|email',
            'dob' => 'required|date',
            'newsletter' => 'required|boolean',
            'country' => 'sometimes|required|in:'.implode(',', Config::get('validation.countries')),
            'street' => 'sometimes|required|string|max:255',
            'zip' => 'sometimes|required|string|between:4,5',
            'city' => 'sometimes|required|string|between:4,255',
            'amount' => 'required|numeric|between:1,'.Config::get('donations.max'),
            'type' => 'required|in:oo,monthly',
            'provider' => 'sometimes|string|nullable',
            'product_id' => 'sometimes|exists:products,id|nullable',
            'campaign_id' => 'required|exists:campaigns,id',
            'status' => 'sometimes|required|in:pending,canceled,success,error',
            'profile' => 'sometimes|string|regex:/^profile[0-9]+$/|nullable',
        ];
    }

    /**
     * Get the validation attributes that apply to the request.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            //
        ];
    }

    /**
     * Get the validation messages that apply to the request.
     *
     * @return array
     */
    public function messages()
    {
        return [
            //
        ];
    }

    private function prepareForValidation()
    {

        dd('getValidatorInstance custom');

        $this->sanitizeInput();

        return parent::getValidatorInstance();
    }

    private function sanitizeInput()
    {

        dd('sanitizeInput custom');

        $data = $this->all();

        dd($data);

        // overwrite the newsletter field value to match boolean validation
        $data['newsletter'] = ($data['newsletter'] == 'true' || $data['newsletter'] == '1' || $data['newsletter'] == true) ? true : false;

        return $data;
    }

    private function validate() {
        dd('validate');
    }
}

As you can see, I first tried to override the getValidatorInstance method, since this looked like the common aproach to this, but it is not executed (so not overridden - protected?).

like image 597
Thomas Venturini Avatar asked Feb 28 '17 10:02

Thomas Venturini


People also ask

What is the method used to configure validation rules in form request laravel?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.

What is bail in laravel validation?

The bail validation rule applies to a "multi-rule" attribute. It does not stop running validation for other attributes. From the documentation: $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]);

What is the method used for specifying custom messages for validator errors in form request?

After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.


2 Answers

Although I didn't tried but it seems it should work you can override validationData from Illuminate\Foundation\Http\FormRequest class like.

/**
 * Get data to be validated from the request.
 *
 * @return array
 */
protected function validationData()
{
    $all = parent::validationData();
    //e.g you have a field which may be json string or array
    if (is_string($playerIDs = array_get($all, 'player_id')))
        $playerIDs = json_decode($playerIDs, true);

    $all['player_id'] = $playerIDs
    return $all;
}

or you can override all method in Illuminate\Http\Concerns\InteractsWithInput trait

/**
 * Get all of the input and files for the request.
 *
 * @return array
 */
public function all()
{
    $all = parent::all();
    //then do your operation
    if (is_string($playerIDs = array_get($all, 'player_id')))
        $playerIDs = json_decode($playerIDs, true);

    $all['player_id'] = $playerIDs
    return $all;
}
like image 170
ARIF MAHMUD RANA Avatar answered Sep 30 '22 17:09

ARIF MAHMUD RANA


Could you modify the request?

$request->merge(['field' => 'new value']);
like image 24
Tim Jai Avatar answered Sep 30 '22 19:09

Tim Jai