Ilya Yaremchuk Ilya Yaremchuk - 28 days ago 9
PHP Question

How to check email (confirmed/or no) at login in laravel 5.2?

I use a standart Laravel Authentication.

php artisan make:auth


But I need to check the status of the user email (confirmed/not confirmed). If not confirmed, then an error will be shown in the login page.

Laravel 5.2

Thanks!

Answer

Make a column is_verified with default value 0, and another column verification_hash in users table. In AuthController.php

    protected function create(array $data)
    {
    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'verification_hash' => md5($data['name'] . Carbon::now()->timestamp),
        'is_verified' => 0,
    ]);
   }

override register method to send him mail with Verification link

public function register(Request $request)
{
    $validator = $this->validator($request->all());

    if ($validator->fails()) {
        $this->throwValidationException(
            $request, $validator
        );
    }

    $user = $this->create($request->all());
    Auth::guard($this->getGuard())->login($user);

    // Send verification email
    // use $user->verification_hash to generate link
    return redirect($this->redirectPath());
}

Now this verification link should look like below as it contain a hash specific to that user

http://your_domain.com/auth/verify/6d533b7664483d3cadd13c23477e4f12

on this link method, change is_verified to 1 for that user.

Now modify your validator method like this

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'username' => 'required|max:255|unique:users',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
        'is_verified'=>'in:1'
    ]);
}

This will allow only those users to login who have is_verified value as 1.

Hope this helps.