Laravel has powerful and elegant validation features like unique/ignore/where. And Backpack’s CRUD controllers allow for invoking Laravel validation from within the controller.
It’s clear to me how to invoke simple validation rules like required
within the Backpack controller. But what about something complex like
Rule::unique('users')
->ignore($user->id)
->where(function ($query) {
return $query->where('location_id', 1);
})
Is there a way to invoke that complex validation from within a Backpack CRUD controller? Or is this a case where I must define the validation in the Request, not the CRUD controller?
Is there documentation somewhere that defines which specific Laravel validation techniques are possible within a Backpack controller, and which aren’t?
3
Answers
Thank you, @christmex. You definitely got me pointed in the right direction.
After much more research and tinkering, I got the following working in the CRUD controller for the Groups table:
This works well --
name_group
is required, and it must be unique, and the above code makes Backpack behave accordingly.So it's looking like the answer to my original question is No, there are no limits to validations in a Backpack controller. If you can express it using Laravel's
Rule::
facade, you can set it in a Backpack controller.However, I'm going to continue work on this pattern, as I'm not exactly clear whether this exact pattern will interact properly with other validations on other fields. You may indeed be able to set any validation in a Backpack controller, but there may be some specific coding rules you have to follow.
We'll see ... I'll report back later.
try this one, let me know if it works for you.
change the ‘username’ to your specific field
Reference: https://backpackforlaravel.com/docs/5.x/release-notes#quickly-validate-forms-inside-crudcontroller-no-formrequest-need
After further testing, I’ve determined that there are indeed some more rules to follow. But first, here’s a more extensive pattern that works fine:
So the rules seem to be:
You can use
setValidation()
on a field-by-field basis within a controller. Each call tosetValidation()
appears to be cumulative with respect to earlier calls, so nothing gets lost when you callsetValidation()
a second time.Within that same controller, a field with simpler validation needs can use
->validationRules()
instead ofsetValidation()
. In other words, you can mix-and-match freely on a field-by-field basis within a given controller.What you cannot do is use both validation techniques for a single field! My testing suggests that
setValidation()
"wipes out" anyvalidationRules()
on the most recentCRUD::field()
statement. So as long as you don’t mix-and-match validation techniques within a single field you should be fine.If someone who is expert in the internals of Backpack could comment on whether everything I wrote above is correct and complete, or not, that would be very helpful to all Backpack users, I’m sure. Thanks!