Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend validation form request in Laravel 5.2?

Tags:

php

laravel

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

like image 556
Dark Cyber Avatar asked Oct 28 '16 15:10

Dark Cyber


People also ask

What is the method used to configure validation rules in form request laravel?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


1 Answers

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',
        ];
    }
}
like image 165
baikho Avatar answered Oct 13 '22 01:10

baikho