How can I add a join to a custom exists rule for a laravel validator?

后端 未结 1 1674
醉话见心
醉话见心 2021-01-06 07:17

The validator in laravel can have a customization of the exists database rule, for instance if you need to check an extra column. An example from the manual:



        
相关标签:
1条回答
  • 2021-01-06 07:21

    It seems that the DatabaseRule does some magic with whatever you provided in that closure. In the end, it only seems to look at provided where clauses (see Exists::__toString). The joins have been saved as the echo inside the closure shows, but then the exists rule only looks at the where. That's the reason for the unknown column error it seems.

    I did try the using function, which seems better suited than the where I had in there first, but that doesn't help, as the system makes it into a string, which forms a validation-string that just doesn't seem to support joins.

    Long story short, I just created a custom validation rule with the passes function looking something like this:

    public function passes($attribute, $value)
    {
        $count = DB::table('staff')
            ->join('teams', 'teams.team_id', '=', 'staff.team_id')
            ->where([
                ['teams.active', '=', 1],
                ['staff.email', '=', $value]
            ])->count();
    
        return $count > 0;
    }
    
    0 讨论(0)
提交回复
热议问题