Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a user email already exist

Tags:

php

laravel

In laravel, when a new user is registering to my site and the email they use already exist in the database. how can tell the user that the email already exist ?. I am new to laravel framework. A sample code would be nice too.

like image 317
ballerz Avatar asked Jul 22 '13 23:07

ballerz


3 Answers

The validation feature built into Laravel lets you check lots of things, including if a value already exists in the database. Here's an overly simplified version of what you need. In reality you'd probably want to redirect back to the view with the form and show some error messages.

// Get the value from the form
$input['email'] = Input::get('email');

// Must not already exist in the `email` column of `users` table
$rules = array('email' => 'unique:users,email');

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    echo 'That email address is already registered. You sure you don\'t have an account?';
}
else {
    // Register the new user or whatever.
}

);

Laravel has built-in human readable error messages for all its validation. You can get an array of the these messages via: $validator->messages();

You can learn more about validation and what all you can do with it in the Laravel Docs.

like image 180
Ed Rands Avatar answered Oct 17 '22 15:10

Ed Rands


Basic Usage Of Unique Rule

'email' => 'unique:users'

Specifying A Custom Column Name

'email' => 'unique:users,email_address'

Forcing A Unique Rule To Ignore A Given ID

'email' => 'unique:users,email_address,10'

Adding Additional Where Clauses

You may also specify more conditions that will be added as "where" clauses to the query:

'email' => 'unique:users,email_address,NULL,id,account_id,1'

The above is from the documentation of Laravel

You could add:

public static $rules = [
    'email' => 'unique:users,email'
];

You can add more rules to the $rules like:

public static $rules = [
        'email' => 'required|unique:users,email'
];

It will automatically produce the error messages

and add:

public static function isValid($data)
{
    $validation = Validator::make($data, static::$rules);

    if ($validation->passes())
    {
        return true;
    }
    static::$errors = $validation->messages();
    return false;
}

to the model User.php

Then in the function you're using to register, you could add:

if ( ! User::isValid(Input::all()))
{
    return Redirect::back()->withInput()->withErrors(User::$errors);
}
like image 11
Loko Avatar answered Oct 17 '22 15:10

Loko


if(sizeof(Users::where('email','=',Input::get('email'))->get()) > 0) return 'Error : User email exists';
like image 8
munzx Avatar answered Oct 17 '22 13:10

munzx