beauraines
beauraines

Reputation: 3

Using Laravel Exists Validation with a condition specified with a function

I have a model where I am attempting to use a exists validation rule like

public static $rules =  ['item' => 'exists:items,item,company_id,\Auth::user()->active_company',
                          'location' => 'exists:locations,location,company_id,\Auth::user()->active_company',
            ];

This validation rule is always failing.

        $validation = Validator::make($this->attributes, static::$rules);

If I modify the rule for the specific user->active_company, it works.

public static $rules =  ['item' => 'exists:items,item,company_id,17',
                          'location' => 'exists:locations,location,company_id,17',
            ]; 

It seems as if the function \Auth::user()->active_company isn't being evaluated when the rules are being checked. All of the examples I've seen use a constant rather than a function.

Will this work with laravel validation or do I need to take a different strategy?

Upvotes: 0

Views: 3289

Answers (1)

Ben Swinburne
Ben Swinburne

Reputation: 26467

The encapsulation of the rules in single quotes means that the contents are taken literally. This means that the validation rule is looking for a company ID which is literally '\Auth::user()->active_company' as opposed to the output of that, perhaps 1 for the sake of example.

See the single quoted strings manual page

There are few ways you could do it:

  • Break out of the quotes and concatenate the two strings with a period (.)

    public static $rules = [
        'item'     => 'exists:items,item,company_id,'.\Auth::user()->active_company,
        'location' => 'exists:locations,location,company_id,'.\Auth::user()->active_company,
    ];
    
  • Write active_company to a variable and break out of the quotes and concatenate the two strings with a period (.)

    $activeCo = \Auth::user()->active_company;
    
    public static $rules = [
        'item'     => 'exists:items,item,company_id,'.$activeCo,
        'location' => 'exists:locations,location,company_id,'.$activeCo,
    ];
    
  • Write active_company to a variable and use double quotes as variables are expanded/interpreted inside double ones. "$activeCo" or "{$activeCo}" will work

    $activeCo = \Auth::user()->active_company;
    
    public static $rules = [
        'item'     => "exists:items,item,company_id,{$activeCo}",
        'location' => "exists:locations,location,company_id,{$activeCo}",
    ];
    

Upvotes: 1

Related Questions