Thứ Ba, 1 tháng 11, 2016

Laravel 5.5 Tutorial : Email Verification for New User After Registration in Laravel 5


Laravel 5.5 tutorial  - How to send an email verification for new members/user after registration in our Laravel 5.3 project? at the previews lessons, we have learn how to create simple email verification we will using "jrean" packages, please read Sending an email verification after registering new user.

In this lessons, we will create new simple project Mail Verification without "jrean" packages.

Video tutorial Email Verification for New User After Registration in Laravel 5.5


Email Verification Project

First, create new project,

composer create-project --prefer-dist laravel/laravel verification

Create Auth using scaffold

php artisan make:auth

Create Connection to Database
Email Verification for New User After Registration in Laravel 5.3
Setting your .ENV files,

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_activation
DB_USERNAME=root
DB_PASSWORD=yourpassword


MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=tls

more detail how to configure mail How to send mail using Gmail SMTP

Create Migration

php artisan make:migration create_users_activation_table

Your migration file is stored here database\migrations\2016_11_01_152432_create_users_activation_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersActivationTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('user_activations', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('id_user')->unsigned();
        $table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
        $table->string('token');
        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
      });

      Schema::table('users', function (Blueprint $table) {
          $table->boolean('is_activated')->default(0);
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
      Schema::drop("user_activations");
      Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('is_activated');
      });
    }
}

User Model

protected $fillable = [
        'name', 'email', 'password', 'is_activated',
    ];


Next, migrate our new table

php artisan migrate

Add New Routes

Route::get('/user/activation/{token}', 'Auth\RegisterController@userActivation');

Add Controller (app\Http\Controllers\Auth\RegisterController.php)

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use DB;
use Mail;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return IlluminateContractsValidationValidator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
    public function register(Request $request) {
      $input = $request->all();
      $validator = $this->validator($input);

      if ($validator->passes()){
        $user = $this->create($input)->toArray();
        $user['link'] = str_random(30);

        DB::table('user_activations')->insert(['id_user'=>$user['id'],'token'=>$user['link']]);

        Mail::send('emails.activation', $user, function($message) use ($user){
          $message->to($user['email']);
          $message->subject('www.hc-kr.com - Activation Code');
        });
        return redirect()->to('login')->with('success',"We sent activation code. Please check your mail.");
      }
      return back()->with('errors',$validator->errors());
    }

    public function userActivation($token){
      $check = DB::table('user_activations')->where('token',$token)->first();
      if(!is_null($check)){
        $user = User::find($check->id_user);
        if ($user->is_activated ==1){
          return redirect()->to('login')->with('success',"user are already actived.");

        }
        $user->update(['is_activated' => 1]);
        DB::table('user_activations')->where('token',$token)->delete();
        return redirect()->to('login')->with('success',"user active successfully.");
      }
      return redirect()->to('login')->with('Warning',"your token is invalid");
    }
}

Add Message in View (resources\views\auth\login.blade.php)

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
                        {{ csrf_field() }}

                        @if ($message = Session::get('success'))
                          <div class="alert alert-success">
                            <p>
                              {{ $message }}
                            </p>
                          </div>
                        @endif
                        @if ($message = Session::get('warning'))
                          <div class="alert alert-warning">
                            <p>
                              {{ $message }}
                            </p>
                          </div>
                        @endif
                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember"> Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="{{ url('/password/reset') }}">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Create new Folder (resources/views/emails/activation.blade.php)

Wellcome, {{ $name }}
Please active your account : {{ url('user/activation', $link)}}

Finally, try to register and check your email, you will get a new mail for verification your new account, and then please login.

Video tutorial Email Verification for New User After Registration in Laravel 5.3



How to Create Blog Using laravel 5.3



Download Full source code here https://goo.gl/flna2j

Không có nhận xét nào:

Đăng nhận xét