Validation in the Laravel

Asked

Viewed 1,751 times

2

I’m wearing a Form Request Validation to validate a form, but when I leave a field of the typerequired blank no error is generated.

How do I generate an error when validation fails ?

class SaleRequest extends FormRequest
{
   public function authorize()
   {
       return true;
   }
   public function rules()
   {
        return [
            'vendor_id' => 'numeric|required',
            'price'     => 'numeric|required',
            'name'      => 'string|required',
        ];
   }
}

Route:

Route::post('/api/list/new/sale', 'SalesController@insert');

Controller:

public function insert(SaleRequest $request)
{
    $vendorInformation = $this->sale->insert($request->all());

    return response()->json($vendorInformation);
}

Model:

public function insert($request)
{
     $request['comission'] = $request['price'] * 0.085;
     $sale = $this->create($request);
     return $this->informationVendor($sale->attributes['id']);
}

public function informationVendor($idSale)
{
    return $this->join('vendors', 'vendors.id', '=', 'sales.vendor_id')
                ->where('sales.id', $idSale)
                ->select('vendors.name', 'vendors.email', 
                         'sales.name', 'sales.price', 'sales.comission')
                ->get();
    }
}
  • what is the version of your language ?

  • 5.4, no view, I am returning a json directly from the controller

  • edited the question

  • @Davidsantos you send this data via ajax? and want a return if you have problems with validation?

  • i am using Postman to make the requests, wanted to return some error if the validation failed

1 answer

2


In the method of controller, do not use with FormRequest, because in your case it won’t work, so do as an example below:

Add the namespace below that is op FACADE responsible for Validator:

use Illuminate\Support\Facades\Validator;

Altered code:

public function insert(Request $request)
{
    $validator = Validator::make(
        $request->all(),
        [
            'vendor_id' => 'required|numeric',
            'price'     => 'required|numeric',
            'name'      => 'required|string',
        ]);

    if ($validator->fails())
    {
        return response()
            ->json($validator->errors());
    }
    return response()
        ->json($this->sale->insert($request));
} 

Observing: required is always the first validation.


After this modification you will have response so:

inserir a descrição da imagem aqui

when the model is unsatisfactory, and when you have everything correct you will receive the information like this:

inserir a descrição da imagem aqui

Browser other questions tagged

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