Created
February 10, 2017 22:29
-
-
Save evercode1/c753fd4bb4d5d3a46283b9fb68b6f538 to your computer and use it in GitHub Desktop.
custom validator in form oject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Requests; | |
| use Illuminate\Foundation\Http\FormRequest; | |
| use Illuminate\Http\Request; | |
| use App\Category; | |
| use App\Subcategory; | |
| use Illuminate\Validation\Factory as ValidationFactory; | |
| class WidgetCreateRequest extends FormRequest | |
| { | |
| public function __construct(ValidationFactory $validationFactory) | |
| { | |
| $validationFactory->extend( | |
| 'belongsToCategory', | |
| function ($attribute, $value, $parameters) { | |
| $category_id = request()->input('category_id'); | |
| $verified = Subcategory::where('id', $value) | |
| ->where('category_id', $category_id) | |
| ->exists(); | |
| return 'belongsToCategory' == $verified; | |
| }, | |
| 'Sorry, subcategory does not belong to category!' | |
| ); | |
| } | |
| /** | |
| * Determine if the user is authorized to make this request. | |
| * | |
| * @return bool | |
| */ | |
| public function authorize() | |
| { | |
| return true; | |
| } | |
| /** | |
| * Get the validation rules that apply to the request. | |
| * | |
| * @return array | |
| */ | |
| public function rules() | |
| { | |
| $count = Category::count(); | |
| return [ | |
| 'name' => 'required|unique:widgets|string|max:30', | |
| 'category_id' => "required|numeric|digits_between:1,$count", | |
| 'subcategory_id' => 'required|belongsToCategory' | |
| ]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment