Laravel 5 Validating form request with parameters

I use form request validation, and there are some rules that need external values ​​as parameters.

Here are my validation rules for editing a business profile inside a form request class,

public function rules() { return [ 'name' => 'required|unique:businesses,name,'.$business->id, 'url' => 'required|url|unique:businesses' ]; } 

I can use this on the controller by type, hinting at it.

public function postBusinessEdit (BusinessEditRequest $ request, business-to-business) {

}

But how to pass the $ business object as a parameter to the rule method?

+5
source share
5 answers

Suppose this is your model binding:

 $router->model('business', 'App\Business'); 

You can then reference the Business class from the FormRequest object as follows:

 public function rules() { $business = $this->route()->getParameter('business'); // rest of the code } 

Please note that if you use the form request to create and check for updates, the business variable will be null when creating the record, because your object does not exist yet. Therefore, be careful to make the necessary checks before invoking the properties or methods of an object.

+5
source

This can be a lot. I do this as shown below.

You may have a hidden id field in your business form, for example below

 {!! Form::hidden('id', $business->id) !!} 

and you can get this id in FormRequest , as shown below,

 public function rules() { $businessId = $this->input('id'); return [ 'name' => 'required|unique:businesses,name,'.$businessId, 'url' => 'required|url|unique:businesses' ]; } 
+8
source

For those who switched to laravel 5:

 public function rules() { $business = $this->route('business'); // rest of the code } 
0
source

Say, if we have a scenario, how we want to change our validation rules depends on the type that we pass through the route. For instance:

 app.dev/business/{type} 

For different types of business, we have different verification rules. All we need to do is specify the type of request for our controller method.

 public function store(StoreBusiness $request) { // The incoming request is valid... } 

To request a custom form

 class StoreBussiness extends FormRequest { public function rules() { $type = $this->route()->parameter('type'); $rules = []; if ($type === 'a') { } return rules; } } 
0
source

In Laravel 5.5 at least (did not check old versions), once you have made your explicit binding ( https://laravel.com/docs/5.5/routing#route-model-binding ), you can get your model directly through $ this:

 class StoreBussiness extends FormRequest { public function rules() { $rules = []; if ($this->type === 'a') { } return rules; } } 
0
source

All Articles