To create custom validation in bagisto :-
Step 1: Inside the package where you need to create validation for go in Modal say User model. Create a custom validation rule class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
use Illuminate\Contracts\Validation\Rule; use App\Models\User; class UniqueUserDataRule implements Rule { public function passes($attribute, $value) { // Check if the value is not empty if (empty($value)) { return false; } // Check if the value is unique in the corresponding table return !User::where($attribute, $value)->exists(); } public function message() { // Define your custom validation error message here return 'The :attribute is already taken.'; } } |
In this example, we assume that the user data is stored in a users
table, and you’re using the User
model.
Step 2 : Use the custom validation rule in your controller or form request:
1 2 3 4 5 6 7 8 9 10 11 12 |
use App\Rules\UniqueUserDataRule; public function store(Request $request) { $request->validate([ 'name' => ['required', new UniqueUserDataRule], 'email' => ['required', 'email', new UniqueUserDataRule], 'phone' => ['required', new UniqueUserDataRule], ]); // The validation has passed, continue with your logic } |
In the example above, name
, email
, and phone
are the fields you want to validate. The UniqueUserDataRule
is used for each field, ensuring that the values are required and unique. The required
and email
rules are added to the email
field to enforce required and valid email input.
Make sure to include the namespace of the custom validation rule class at the top of your controller or form request file, like use App\Rules\UniqueUserDataRule;
, depending on the location of your custom validation rule file.
By using this custom validation rule, you can ensure that the user name, email, and phone number fields are both required and unique, displaying the defined error message when the validation fails.
Note: I’ve explored this while contributing to the Laravel-based project Bagisto, you can also learn a lot from the enterprise-level open-source Bagisto and do contribution to it.
Thanks for reading this blog. I hope you’ll get an idea of how to create Custom Datagrid. Please share your reviews on this, that will support me to write more.
Additionally, you can also hire laravel developers to help you with your project requirements and ensure the successful implementation of your ideas. If you want additional features to your e-commerce website, then you can explore our extension.