I created the HunterRequest.php
file to store the error messages from validations and make the methods in my HunterController.php
file not need to load these validation messages, making that take up fewer lines of code and have a cleaner appearance. However, I am not able to return these messages in the form in my validation test because of an error.
HunterRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class HunterRequest 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<string, mixed>
*/
public function rules()
{
return
[
'name_hunter' => 'required|max:50',
'year_hunter' => 'required|numeric',
'height_hunter' => 'required|numeric',
'weight_hunter' => 'required|numeric',
'type_hunter' => 'required|max:30',
'type_nen' => 'required|max:30',
'type_blood' => 'required|max:3',
];
}
// Customizing messages rules
public function messages()
{
return [
'name_hunter.required' => 'Hunter name can't be empty.',
'name.max' => 'Hunter name must be a maximum of 30 characters.',
'year_hunter.required' => 'Hunter year can't be empty.',
'year_hunter.numeric' => 'Hunter age must be a whole number.',
'height_hunter.required' => 'Hunter weight can't be empty.',
'height_hunter.numeric' => 'Hunter weight must be a decimal number.',
'weight_hunter.required' => 'Hunter weight can't be empty.',
'weight_hunter.numeric' => 'Hunter weight must be a decimal number.',
'type_hunter.required' => 'It is necessary to define the type of Hunter.',
'type_hunter.max' => 'Hunter type must be a maximum of 30 characters.',
'type_nen.required' => 'It is necessary to define the type Nen.',
'type_nen.max' => 'Nen type must be a maximum of 30 characters.',
'type_blood.required' => 'It is necessary to define the type blood.',
'type_blood.max' => 'Blood type must be a maximum of 3 characters.',
];
}
}
HunterController.php
namespace App\Http\Controllers;
use App\Http\Requests\HunterRequest;
use Illuminate\Http\Request;
use App\Models\HunterModel;
class HunterController extends Controller {
public function store(Request $request)
{
$validacoes = $request->validate();
HunterModel::create($validacoes);
return redirect()->to('/');
}
public function update(Request $request, $id)
{
$validacoes = $request->validate();
HunterModel::where('id',$id)->update($validacoes);
return redirect()->to('/');
}
}
CodePudding user response:
You need to actually make use of your custom request. So change your parameter type hint(s) from Request
to HunterRequest
.
public function store(HunterRequest $request)
{
$validacoes = $request->validated();
HunterModel::create($validacoes);
return redirect()->to('/');
}
public function update(HunterRequest $request, $id)
{
$validacoes = $request->validated();
HunterModel::where('id',$id)->update($validacoes);
return redirect()->to('/');
}