4

I have some validation on my form in laravel to ensure the gift the user is claiming is one assigned to their campaign with the below code

'gift_id' => 'required|int|exists:gifts,campaign_id,' . \Auth::user()->campaign->id,

But on form submission I am getting the following error

ErrorException in ValidatesAttributes.php line 721: Undefined offset: 1

Could someone please help me out?

Thanks

Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73
user6073700
  • 230
  • 4
  • 17
  • I don't understand what the exists rule is meant to check – apokryfos Mar 30 '17 at 10:51
  • @apokryfos It's to check if something exists... – Ian Mar 30 '17 at 10:51
  • @Ian not in the abstract, in this particular case – apokryfos Mar 30 '17 at 10:51
  • It basically queries that the gift with the campaign_id is the same as the campaign id of the user. (Ensuring that a user can only claim a gift which is relevant to their campaign) – user6073700 Mar 30 '17 at 10:52
  • 1
    @user6073700 i don't think `exists` would do that for you, you probably need a custom rule. – apokryfos Mar 30 '17 at 10:52
  • Why wouldn't it? Exists allow where clauses as well like the above, it just concatenates the condition from the Auth::user campaign relationship – user6073700 Mar 30 '17 at 10:53
  • Are you using a Request to handle the validation? If so fluent rules may be up your alley. http://stackoverflow.com/documentation/laravel/1310/validation/9670/other-validation-approaches#t=201703301054121552488 – Ian Mar 30 '17 at 10:54

2 Answers2

11

The Laravel application I'm currently working on started to throw that exception. In my case, the issue was slightly different. This was my original code:

// ...

'extension_id' => [
    'nullable',
    'int',
    Rule::exists('extensions,id'),
],

// ...

I added that ,id to the table name hoping that the correct column name was used when the framework checks the value existence. However, it didn't work as expected. I got that exception from Illuminate\Validation\Concerns\ValidatesAttributes class.

Undefined offset: 1

After some attempts, I finally was able to overcome the error by passing two arguments to the rule, instead of a single string:

Rule::exists('extensions', 'id'),

I know that's not the same case as the OP, but I guess it can help others that reach this same question as I did.

Gustavo Straube
  • 3,744
  • 6
  • 39
  • 62
2

You need a more custom exists rule. According to the docs exists as a string can only handle the existence of a specific input value in the specific column:

'gift_id' => [
    'required',
    'int',
    Rule::exists('gifts')->where(function ($query) {
        $query->where('campaign_id', \Auth::user()->campaign->id);
    }),
],

or something to this effect.

apokryfos
  • 38,771
  • 9
  • 70
  • 114