Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing model-stored validation rules in Laravel

Let's say, I have a User model in Laravel like this:

class User extends Eloquent implements UserInterface, RemindableInterface {

    public static $rules = array(
        'email' => 'required|email',
        'password' => 'required|min:8|confirmed',
        'password_confirmation' => 'required|min:8'
    );

    ...

}

Rules, stored in model, will be reused both for login and register forms but problem occurs when there's no need for password confirmation (e.g. login form). And there could be many such situations where the rules should be changed.

So, is there any pure method how to modify model-stored validation rules for different cases in Laravel? Do I have to reorganize my rule storage approach at all?

Thanks!

like image 559
arnisritins Avatar asked Nov 27 '22 04:11

arnisritins


1 Answers

You can add rules dynamically when you need them.

For example:

If I am right, you only need the password_confirmation rule when registering a user and when updating a password. So, in your model, do not add the password_confirmation rule .

public static $rules = array(
        'email' => 'required|email',
        'password' => 'required|min:8|confirmed'

}

How to add the rule dynamically:

To register a user, the password_confirmation field is required. So, from your controller, you can always add rules like the following:

$rules = User::$rules;

$rules['password_confirmation'] = 'required|min:8';

and sometimes you may need to add rules based on user input.

For example:

If a user selects Australia as country, they must also select a state.

$v = Validator::make($data, $rules ));
$v->sometimes('state', 'required', function($input)
{
   return $input->country == 'Australia';
});
like image 160
Anam Avatar answered Feb 11 '23 10:02

Anam