Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Form request validation with parameters

I am using form request validation and there are some rules that needs external values as a 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 it.

public function postBusinessEdit(BusinessEditRequest $request, Business $business)
{
    //
}

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

like image 509
Dipendra Gurung Avatar asked Jul 16 '15 01:07

Dipendra Gurung


2 Answers

Lets say this is your model binding:

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

Then you can reference the Business class from within the FormRequest object like this:

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

Note that if you use your form request both for create and update validation, while creating the record, the business variable will be null because your object does not exists yet. So take care to make the needed checks before referencing the object properties or methods.

like image 112
Sh1d0w Avatar answered Oct 10 '22 15:10

Sh1d0w


Since Laravel 5.6 you may type hint it in the rules method:

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

See the docs for more:

You may type-hint any dependencies you need within the rules method's signature. They will automatically be resolved via the Laravel service container.

like image 45
Adam Avatar answered Oct 10 '22 14:10

Adam