'The custom messages doesn't returned from FormRequest in my app based on Laravel 9.8.1
Next is my FormRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreFruitRequest 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()
{
return [
'name' => 'required|string|min:3',
'carbohydrates' => 'required|numeric|gte:0',
'protein' => 'required|numeric|gte:0',
'fat' => 'required|numeric|gte:0',
'calories' => 'required|integer|numeric|gte:0',
'sugar' => 'required|numeric|gte:0',
];
}
/**
* Error Messages
*
* @return array
*/
public function messages() :array
{
return [
'carbohydrates.gte' => 'Nutrients cannot be negative',
'protein.gte' => 'Nutrients cannot be negative',
'fat.gte' => 'Nutrients cannot be negative',
'calories.gte' => 'Nutrients cannot be negative',
'sugar.gte' => 'Nutrients cannot be negative',
];
}
}
The validation rules work fine but when I make the request with the wrong value, which is a negative amount, validation does not return these messages to the controller. So, my API returns the main blade page as an error.
What is incorrect in my code? Or, do I need some tunings anywhere?
Controller (as an answer for @NickSdot):
/**
* Store a newly created resource in storage.
*
* @param StoreFruitRequest $request
* @return JsonResponse
*/
public function store(StoreFruitRequest $request)
{
return response()->json(Fruit::create($request->all()) ?? "Cannot create fruit $request->name");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
