Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating boolean with Laravel Validation

I have a login form with

username, password and remember me

remember me is a checkbox (true or false).

How do I create the validation rule in Laravel? http://laravel.com/docs/validation#basic-usage

The only relevant one it seems was in and you specify the values but the values in this case are booleans and using this method they would be specified as string?

in:true,false

like image 512
user391986 Avatar asked Apr 21 '14 15:04

user391986


2 Answers

There's a validator for boolean. Assuming you're using one of the packages that simplifies model validation, e.g. EsensiModel, it's as simple as adding the following to your Model:

protected $rules = [
    'email'       => 'required|email',
    'password'    => 'required',
    'remember_me' => 'boolean',
];
like image 116
morphatic Avatar answered Oct 17 '22 15:10

morphatic


You may try something like this:

$rules = array('email' => 'required|email', 'password' => 'required');
$inputs = array(
    'email' => Input::get('email'),
    'password' => Input::get('password')
);
$validator = Validator::make($inputs, $rules);

if($validator->fails()) {
    return Redirect::back()->withInput()->withErrorts($validator);
}
else {
    $remember = Input::get('remember', FALSE);
    if(Auth::attempt($inputs, !!$remember)) {
        // Log in successful
        return Redirect::to('/'); // redirect to home or wherever you want
    }
}

I've used email which is recommended but if you use username other than email then just change the email to username and in the rule for username use something like this:

'username' => 'required|alpha|min:6' // Accepts only a-z and minimum 6 letters
like image 3
The Alpha Avatar answered Oct 17 '22 17:10

The Alpha