Search code examples
phpvalidationlaravel-5

laravel 5 double validation and request


I did this validation and works:

public function salvar(CreateEquipamento $Vequip, CreateLocalizacao $VLocal)
    {
        $this->equipamento->create($Vequip->all());

        $equipamento = $this->equipamento->create($input);   

        return redirect()->route('equipamento.index');
    }

what I want is to also do something like get the last created equipment ID and include in the array to validate and create for Local validation (CreateLocalizacao $VLocal) because i've two tables, one for the equipment and another one who stores all the places where my equipment was in.

$input['equipamento_id'] = $equipamento->id;

$this->localizacao->create($VLocal->all());

How could I do something like this?? thx in advance !

I do a "workarround" solution ;)

$localizacao = [
                'equipamento_id' => $id,
                'centrocusto_id' => $input['centrocusto_id'],
                'projeto' =>  $input['projeto'],
                'data_movimentacao' =>  $input['data_movimentacao']
                ];

$this->localizacao->create($VLocal->all($localizacao)); 

I dont know if this is the best way to do it but works, but if somebody has the right way to do post please!


Solution

  • Are you using Laravel 5?

    If yes, use form Requests, they make everything easier. If you need to validate two things from one form, you just put two requests in the controller method. I use this when I register an user for an ecommerce page. I need to validate the user data and the address data, like this:

    public function store(UserRegisterRequest $user_request, AddressCreateRequest $add_request)
    {
        //if this is being executed, the input passed the validation tests...
        $user = User::create(
           //... some user input...
        ));
    
        Address::create(array_merge(
          $add_request->all(),
          ['user_id' => $user->id]
        ));
    }}
    

    Create the request using artisan: php artisan make:request SomethingRequest, it generates an empty request (note the authorize function always returns false, change this to true or code that verifies that the user is authorized to make that request).

    Here's an example of a Request:

    class AddressCreateRequest extends Request {
      public function authorize()
      {
        return true;
      }
    
      public function rules()
      {
        return [
           "fullname"  => "required",
           //other rules
        ];
      }
    
    }
    

    More on that on the docs: http://laravel.com/docs/5.0/validation#form-request-validation