Create Custom Validation Rule with additional Parameters - implement in Request

Posted 1 year ago by longestdrive

Hi I'm trying to add a custom validation rule to a Laravel 5.5 app.

I've created a rule using php artisan make:rule and am struggling getting it to work so I can build on it. I've looked at the docs here: https://laravel.com/docs/5.6/validation#custom-validation-rules

This goes on to use this in a controller, implies you can use it in a request but doesn't say how.

My rule will check whether the ticket has been used and if it has pass if it is for this id or fail if it is for another id. So it needs the ticket number and the parent record id.

Here's the rule skeleton:

    <?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class TicketNumberIsNotUsed implements Rule
{


    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        dd($value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}

and here's how I'm trying to implement in my request:

    public function rules()
    {
        return [
            'play_date'=>'required',
            'am_tee'=>'required',
            'howBooked'=>'required',
            'ticket'=>['required|exists:ticket_audits,ticketnumber' , new TicketNumberIsNotUsed()] ,
            'pay_method'=>'required',
            'customer_id'=>'required:exists:customers,id'

        ];
    }

The error I get is Method [validateRequired|exists] does not exist.

so by including the way I have corrupts the rules.

I've tried looking for tutorials which all point towards extending the validator class and using the AppServiceProvider but trying to avoid this route and follow the guidance in the docs.

I've tried this approach for the rules but it doesn't appear to fire:

public function rules()
    {
        return [
            'play_date'=>'required',
            'am_tee'=>'required',
            'howBooked'=>'required',
            'ticket'=>'required|exists:ticket_audits,ticketnumber' , new TicketNumberIsNotUsed() ,
            'pay_method'=>'required',
            'customer_id'=>'required:exists:customers,id'

        ];

Any help appreciated

Please sign in or create an account to participate in this conversation.