Validation in Laravel

2

I'm using Form Request Validation to validate a form, but when I leave a field of type required 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();
    }
}
    
asked by anonymous 12.08.2017 / 03:03

1 answer

2

In the controller method, do not use with FormRequest , because, in your case it will not work, then, as an example below:

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

use Illuminate\Support\Facades\Validator;

Code changed:

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));
} 

Note: required is always the first validation.

After this change you will get an answer like this:

  

Whenthemodelisnotsatisfactory,andwhenyouhaveeverythingcorrectyouwillreceivetheinformationlikethis:

  

    
13.08.2017 / 02:29