Skip to content

Instantly share code, notes, and snippets.

@secmohammed
Last active March 5, 2019 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secmohammed/d7b4bbdd9829f143ec05e756bd3a14f7 to your computer and use it in GitHub Desktop.
Save secmohammed/d7b4bbdd9829f143ec05e756bd3a14f7 to your computer and use it in GitHub Desktop.
laravel exists rule validation
  • when using the Rule class to check on existence of specific record while validation , a query builder is being returned that can be used for nested checks
Rule::exists('addresses', 'id')->where(function($builder) {
  $builder->where('user_id', auth()->id());
})
                

That's an alternative to creating a couple of "exists" rule like the following:

 [
    'field' => 'exists:table,id',
    'another_field' => 'exists:table,another_id'
 ]

Note: that in user_id scenario, we can't use the second approach as we aren't passing the user_id through the request, therefore it would be better to use the first approach, also it would be better for further complex queries for validation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment