I'm not getting errors even though I have used validate() method using axios.
This is my controller,
public function store(Request $request)
{
$fields = $request->validate([
'product_name' => 'required',
'product_cost' => 'required | integer',
'product_selling' => 'required | integer',
'product_stock' => 'required | integer',
]);
Product::create([
'name' => $fields['product_name'],
'cost' => $fields['product_cost'],
'selling' => $fields['product_selling'],
'stock' => $fields['product_stock'],
]); }
This is my Vue file
const productState = reactive({
product_name: "",
product_cost: "",
product_markup: "",
markup_type: "Markup by price",
product_selling: "",
product_stock: "",
returned_errors: [],
});
axios .post("api/products", productState)
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error.response.data.errors));
Even if it has errors still it returns the response.
try {
$fields = $request->validate([
'product_name' => 'required',
'product_cost' => 'required | integer',
'product_selling' => 'required | integer',
'product_stock' => 'required | integer',]);
} catch (ValidationException $ex) {
return response()->json(['errors' =>$ex->errors()], 422); //what ever error format that you desire
}
You should try catch
the $request->validate
and send the custom response back, if you are sending API request.
But I don't suggest using $request->validate
API requests you can go for Form Request or Validator::make()
for more flexibility for api requests too and also you can catch the validation exception in the Handler.php
file too and handle it there.
There are lots of articles already posted so try to research "Larvel Validation for API requests". (I am not gonna link to the specific articles you can find Youtube videos Medium articles to blog posts)
It will help you to understand the Laravel validation process as a whole.