Marco Bozzola
Marco Bozzola

Reputation: 189

laravel and validation with request

I cannot set correctly validation in Laravel. Among other functions I have this in the Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\RimborsiExport;

use DB;
use App\Customers;
use App\Claims;
use App\Refunds;
use App\Services;
use App\Http\Requests\RefundsPost;

use Excel;
use DataTables;
use Redirect;
use Response;

class RefundsController extends Controller
{
    public function storeRefundsData(RefundsPost $request){
        dd($request);
        
        //$validated = $request->validated();
        $customers = Customers::create($request->all());
        return back()->with('status', 'Dati Cliente inseriti correttamente');
    }

}

I have also defined a custom Request type

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RefundsPost extends FormRequest
{
    /**
     * 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()
    {
        $rules = [
            'contr_nom' => 'required|max:255',
            'contr_cog' => 'required',
            'polizza' => 'required',
            'email' => 'required',
            'targa' => 'required',
            'iban' => 'required|iban',
            'int_iban' => 'required',
        ];
        return $rules;
    }
    
    public function messages()
    {
    return [
        'contr_nom.required' => "Il Nome Contraente e' obbligatorio",
        'contr_cog.required'  => "Il Cognome Contraente e' obbligatorio",
        'polizza.required'  => "Il numero di polizza e' obbligatorio",
        'email.required'  => "Una mail e' obbligatoria per le comunicazioni",
        'targa.required'  => "La targa e' obbligatoria",
        'data_sin.required'  => "La data sinistro e' obbligatoria",
        'iban.required'  => "Il numero IBAN e' obbligatorio",
        'int_iban.required'  => "L'intestatario dell' IBAN e' obbligatorio",
        'dossier.required'  => "Il numero di dossier e' obbligatorio",
        'cliente.required'  => "Il cliente e' obbligatorio",
        'stato.required'  => "Lo stato del rimborso e' obbligatorio",
        'date_ref.required'  => "La data della richiesta e' obbligatoria",
        ];
    }
}

and i have this blade with the form inside

    <div class="container-fluid">
  <form method="POST" action="{{ route('storeRefundsData') }}" novalidate>
      
    {{ csrf_field() }}

    <h5 class="mb-3">Anagrafica</h5>      
    <div class="row">
      <div class="col-md-6 mb-3">
        <label for="contr_nom">Nome Contraente</label>
        <input type="text" class="form-control @error('contr_nom') is-invalid @enderror" id="contr_nom" name="contr_nom" value="{{old('contr_nom')}}">
        @error('contr_nom')
          <div class="invalid-feedback">{{ $message }}</div>
        @enderror
      </div>
      <div class="col-md-6 mb-3">
        <label for="contr_cog">Cognome Contraente</label>
        <input type="text" class="form-control @error('contr_cog') is-invalid @enderror" id="contr_cog"  name="contr_cog" value="{{old('contr_cog')}}">
        @error('contr_cog')
          <div class="invalid-feedback">{{ $message }}</div>
        @enderror
      </div>
    </div>

    <div class="row">
      <div class="col-md-6 mb-3">
        <label for="polizza">Numero Polizza <span class="text-muted"></span></label>
        <input type="text" class="form-control @error('polizza') is-invalid @enderror" id="polizza" name="polizza" value="{{old('polizza')}}">
        @error('polizza')
          <div class="invalid-feedback">{{ $message }}</div>
        @enderror
      </div>

      <div class="col-md-6 mb-3">
        <label for="email">Email <span class="text-muted"></span></label>
        <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" placeholder="[email protected]" value="{{old('email')}}">
        @error('email')
          <div class="invalid-feedback">{{ $message }}</div>
        @enderror
      </div>
    </div>

    <div class="row">
      <div class="col-md-6 mb-3">
        <label for="targa">Targa veicolo</label>
        <input type="text" class="form-control @error('targa') is-invalid @enderror" id="targa" name="targa" placeholder="Inserisci la targa" value="{{old('targa')}}">
        @error('targa')
          <div class="invalid-feedback">{{ $message }}</div>
        @enderror
      </div>          
    </div>
    
    <h5 class="mb-3">Dati bancari</h5>
    <div class="row">
      <div class="col-md-6 mb-3">
        <label for="iban">IBAN <span class="text-muted"></span></label>
        <input type="text" class="form-control @error('iban') is-invalid @enderror" id="iban" name="iban" placeholder="Inserisci il tuo IBAN" value="{{old('iban')}}">
        @error('iban')
          <div class="invalid-feedback">{{ $message }}</div>
        @enderror
      </div>

      <div class="col-md-6 mb-3">
        <label for="int_iban">Intestatario IBAN <span class="text-muted"></span></label>
          <input type="text" class="form-control @error('int_iban') is-invalid @enderror" id="int_iban" name="int_iban" placeholder="Inserisci l'intestatario dell'IBAN" value="{{old('int_iban')}}">
          @error('int_iban')
            <div class="invalid-feedback">{{ $message }}</div>
          @enderror
        </div>
      </div>

    <hr class="mb-4">
    <!-- <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>-->
    <input type="submit" class="btn btn-primary btn-lg btn-block" value="Salva">
    
    @if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
    @endif
  </form>
</div>

I cannot understand why when i click on form submit button to create a new row in the db, it seems that even it doesn't enter Controller function. If I use Request instead of custom type RefundsPost it works and store data in the db but obviously without validation. How can i fix? Thx a lot

Upvotes: 4

Views: 15748

Answers (2)

Ali
Ali

Reputation: 21

Unfortunately, I cannot comment.

However, out of curiosity the rule iban is custom I believe right?

If so, can you try the following:

    public function rules()
    {
        return [
            'contr_nom' => ['required', 'max:255'],
            'contr_cog' => ['required'],
            'polizza'   => ['required'],
            'email'     => ['required'],
            'targa'     => ['required'],
            'iban'      => ['required', new Iban],
            'int_iban'  => ['required'],
        ];
    }

Of course, don't forget to import the rule class at the top:

use App\Rules\Iban;

Try it and let us know, cheers!

Upvotes: 0

Andrew Larsen
Andrew Larsen

Reputation: 1267

Not sure if this solves your problem, but I have rewritten your functions the way I would do it. You can specify what http method the rules are for, in this case I specified the rules for POST requests.

RefundsPost -> rules:

public function rules() {
    $rules = [];

    switch($this->method()) {
        case 'POST': 
        {
            $rules = [
                'contr_nom' => 'required|max:255',
                'contr_cog' => 'required',
                'polizza' => 'required',
                'email' => 'required',
                'targa' => 'required',
                'iban' => 'required|iban',
                'int_iban' => 'required',
            ];
        }

        default:
            break;
    }

    return $rules;
}

and in the storeRefundsData function, you should use $request->validated() and use the attributes it return after validation when you proceed the insertion.

RefundsController -> storeRefundsData:

public function storeRefundsData(RefundsPost $request) {

    $attributes = $request->validated();

    $customers = Customers::create($attributes);

    if (!($customers instanceof Customers)) {
        // could not create customer
        return ['result' => false];
    }

    $customers = $customers->fresh(); // if you need to retrieve the objects id

    return ['result' => true];
}

Upvotes: 1

Related Questions