Dark Cyber Dark Cyber - 1 month ago 17
PHP Question

How to extend validation form request in Laravel 5.2?

I have this validation request

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateUserRequest extends Request
{
/**
* 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()
{
return [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:6',
'full_name' => 'required',
'address' => 'required',
'phone' => 'required|numeric',
'family_name' => 'required',
'family_address' => 'required',
'family_phone' => 'required|numeric',
'idcard' => 'required|image',
];
}
}


I can use it like this in my controller method

public function register(CreateUserRequest $request){
}


Now I have other form which need to be validate but the form have addition field.

I know, I can make new Request which contain field in CreateUserRequest + new field.

But I think this is bad way.

So how I can extend the CreateUserRequest and add the other field?

So I can use in other controller method like this

public function othermethod(otherCreateUserRequest $request){
}


Any help appreciated.

maybe something like this reference mattstaufer laravel 5.0 form request

Answer

You can extend your CreateUserRequest class like this:

<?php

namespace App\Http\Requests;

use CreateUserRequest;

Class OtherCreateUserRequest extends CreateUserRequest {

    public function rules()
    {
        return parent::rules() + [
            'additional' => 'rule',
        ];
    }
}