Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change value of $request before validation in laravel 5.5

I have a form in route('users.create').

I send form data to this function in its contoller:

public function store(UserRequest $request)
{

    return redirect(route('users.create'));
}

for validation I create a class in

App\Http\Requests\Panel\Users\UserRequest;

class UserRequest extends FormRequest
{
    public function rules()
    {
        if($this->method() == 'POST') {
             return [
                 'first_name' => 'required|max:250',

It works.

But How can I change first_name value before validation (and before save in DB)?

(Also with failed validation, I want to see new data in old('first_name')

Update

I try this:

 public function rules()
    {
     $input = $this->all();


     $input['first_name'] = 'Mr '.$request->first_name;
     $this->replace($input);

     if($this->method() == 'POST') {

It works before if($this->method() == 'POST') { But It has not effect for validation or for old() function

like image 293
Maria Avatar asked Oct 06 '17 23:10

Maria


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.


1 Answers

Override the prepareForValidation() method of the FormRequest.

So in App\Http\Requests\Panel\Users\UserRequest:

protected function prepareForValidation()
{
    if ($this->has('first_name'))
        $this->merge(['first_name'=>'Mr '.$this->first_name]);
}
like image 81
numbnut Avatar answered Sep 22 '22 23:09

numbnut