How to implement two Request to validate individual and legal fields?

Asked

Viewed 93 times

0

If the type of person selected is F is valid through the FisicaRequest

public function store(FisicaRequest $reqFisica, JuridicaRequest $reqJuridica)
{
    if ($reqFisica->tipo_pessoa == "F") {

        $data = $reqFisica->all();
        Devedor::create($data);
        return redirect()->route('admin.devedors.index');
    }
    if ($reqJuridica->tipo_pessoa == "J") {

        $data = $reqJuridica->all();
        Devedor::create($data);
        return redirect()->route('admin.devedors.index');
    }
}

However I am not getting the legal entity to be validated by Juridicarequest.

  • uses the request validate and validates how many digits are being passed dom min and max

  • the second request is populated? how does the framework know which object should be injected? I believe that two requests in the same method will not work

  • In Http request, you only have one Request, you can use different validation logics in Formrequest

2 answers

1

In this case you can use a request within the controller.

public function store(Request $request)
{
 if ($request->tipo_pessoa == "F") {
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
}

if ($request->tipo_pessoa == "J") {
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
}

}

0


In itself RequestFormif you can create the decision you want and you don’t need to create two for validation one with one if inside you can have the same effect, example:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PeopleRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $data = array();
        if ($this->get('tipo_pessoa') === 'F')
        {
            // validações da pessoa fisica
            $data[... // validações
        }
        else
        {
           // validações da pessoa jurídica ou diferente de física
           $data[... // validações
        } 
        return $data;
    }
}

In that if(decision) can redeem the element sent by form(form) and this gives you a deviation in the corresponding user type validation.

  • Because I got a negative vote? has some explanation, has something to tidy up or it is simply a way of curb, of persecution, if there is something wrong can say I am here to tidy up too, after all we are all human.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.