phplaravelvalidationlaravel-requestrequest-validation

Laravel: validation message for same rules in one field


I am new to Laravel, and I try to validate a request. I have to following request class:

namespace App\Http\Requests;

class TestRequest extends FormRequest
{
    protected function rules() 
    { 
        return [
            'group_id' => 'required|exists:groups,id,deleted_at,NULL|exists:group_users,group_id,user_id,' . \Auth::user()->id
        ];
    }
}

My problem is:

My question is:

PS: I'm using Laravel 5.3


Solution

  • I would recommend writing a custom rule. Check the below link for where to add it in your code

    https://laravel.com/docs/5.3/validation#custom-validation-rules

    Validator::extend('group_check', function($attribute, $value, $parameters, $validator) {
        // Do custom exists check 1;
        $group = Group::where('id', $value)->where('deleted_at', 'null')->first();
    
        if (!$group) {
            return false;
        }
    
        // Do custom exists check 2;
    });
    
    Validator::replacer('group_check', function($message, $value, $parameters, $validator) {
        // Do custom exists check 1 but instead of returning false, return a custom message
    
        // Do custom exists check 2 return a custom message
    });