I have a store Method for my TransactionController, at the moment it does validate that the required information is received (standard Laravel validation), nonetheless, it can’t check if the value received exists on a third table (since it’s a foreign key).
Store method of TransactionController.php
public function store(Request $request) { $request -> validate([ 'folio' => 'required', 'codigo_referido_id' => 'required', 'descuento_activo_id' => 'required', 'lead_id' => 'required' ]); } [...]
I want to add further validation to ensure that the information received is ready for get stored in the database and if it is not, inform the user with a custom message.
This is done with:
TransactionController.php store Method
[...] if($request['codigo_referido_id']){ if( Empleado::find($request['codigo_referido_id']) ){ // Continue to the next validation }else{ // return to view with the error message [I want to use the default $errors variable to store the error return]. } }
How can I return back to the view sending my custom error message in the else clause?
Advertisement
Answer
You can add custom validation for this instead of if else
$request -> validate([ 'folio' => 'required', 'codigo_referido_id' => ['required', function ($attribute, $value, $fail) { if (!Empleado::find($value)) { $fail('The '.$attribute.' is invalid.'); } }], 'descuento_activo_id' => 'required', 'lead_id' => 'required' ]);
Ref:https://laravel.com/docs/8.x/validation#custom-validation-rules