0

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this is what I was looking for, could you tell me where to find more about this function? In the Laravel docs I found another approach, more complex and no examples given. So I get confused instead of making my way to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.