Tuesday 9 February 2016

Mail Verification Using Laravel 5

In this article i will be showing you how to send a verification email to a user's entered email address. If you listen this process for the first time it sounds like a nightmare but actually if you have a little concept of MVC and laravel architecture then you can easily understand this article and can get a fully automated verification email service on your laravel application.So lets get started.



Requirements

So in order to do this we will have to create just two fields in the sign up form in addition to the fields that are already in the most users table i.e username,email,password,confirm password etc. So first we need a field with boolean data type in order to keep track that whether a user has activated its account or not. This field will be set to false by default.

The second field that we require is a confirmation_code field and its data type is string. When a user registers a new account we generate a random string and then  store this generated field in the database an email will be sent to the user asking him to confirm his/her account by following a link that we will define in our /app/http/routes.php. When a user will click on this link we will take this information we compile it in our code match with our string and then complete the process.

The code i am writing below is of a very simple user's table.  



use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration{    
/**     
* Run the migrations.     
*     
@return void     
*/    
public function up()    {        
Schema::create('users', function (Blueprint $table) {            
$table->;increments('id');            
$table->;string('name');            
$table->;string('email')->;unique();            
$table->;string('password', 60);            
$table->;boolean('confirmed')->;default(0);            
$table->;string('confirmation_code')->nullable();            
$table->rememberToken();            
$table->timestamps();        
});    
}
    
/**     
* Reverse the migrations.     
*     
* @return void     
*/    
public function down()    {        
Schema::drop('users');    
}}

User Registration

Now that the user table is set up we can begin adding our registration functionality. This is same as the normal procedure when the user submits we validate and we store. The real story comes after that when we have to generate a random string that is going to be used as the confirmation_code for the user. We can generate the random string by using a helper function of laravel str_random() in the argument give the number for the length of the generated string. With the confirmation code generated we now have all the information we need to create user. 
Note  If you are using mass assignment with User::create(), You need to set the $fillable property on your user model to contain username, email, password and confirmation code.

Now once the user is created we need to send him his confirmation email. We will use laravel's  Mail::send()   and create very basic email template that will tale the confirmation_code  and output a link to the confirmation URL that the user needs to visit. 

Code For Storing User and Sending Mail 

This code will be written in the controller in my case the controller name is RegistrationController  


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redirect;
use Input;
use Validator;
use App\User;
use Hash;


class RegistrationController extends Controller{    
public function send_mail(){
        $auth = [                
'name' =>'required|min:6',                
'email' =>'required|email|unique:users',                
'password' =>'required|confirmed|min:6',                
'password_confirmation' =>'required|min:6'
 ];        
// Getting Input        
$input = Input::all();

// Performing Validation        
$validator = Validator::make($input, $auth);        
if($validator->fails())
{            
return Redirect::back()->withInput()->withErrors($validator);        }        
// Generating random string        
$confirmation_code = str_random(32);


//Creating User          
$user = User::create([
'name' => Input::get('name'),             
'email' => Input::get('email'),             
'password' => Hash::make(Input::get('password')),             
'confirmation_code' =>  $confirmation_code,
         ]);
 // Sending Mail        
Mail::send('email.verify', array('confirmation_code'=>$confirmation_code), function($message) {$message->to(Input::get('email'), Input::get('username'))->subject('Verify your email address'); });
 // Printing Message
        echo "";
        return view('welcome');

    }
}

The simple verification email using blade is 

<html>
<html lang="en-US">
<head>
 <meta charset="utf-8">
 </head> 
<body>
 <h2>Verify Your Email Address</h2>

<div>
    Thanks for creating an account with the verification demo app.
    Please follow the link below to verify your email address
    {{ URL::to('register/verify/' . $confirmation_code) }}.<br>

<div>

<body>
<html>

User Confirmation
To complete the confirmation process the user must follow the lick that is send to them in their mail. So the route of our link will be such like that

Route::post('register/verify','RegistrationController@send_mail');
Route::get('register/verify/{confirmationCode}'
[    'as' =>'confirmation_path',    
'uses' => 'RegistrationController@confirm']);

Now we need to define a method in the controller which will do a couple of important things. First we need to find the user to which this confirmation code belongs. If no confirmation code is included or the code does not belong to any user then we will redirect back to home page.

If a user is found then we his/her confirmed field to true and set their confirmation_code to null. This is done so that on the off chance the same code is generated and given to two separate users then as long as the first user verified their email address they will no longer have this code set and no problems will arise.

// Confirmation Code
   public function confirm($confirmation_code)   {       
if( ! $confirmation_code)       
{           
throw new InvalidConfirmationCodeException;       
}
$user = User::whereConfirmationCode($confirmation_code)->first();
if ( ! $user)       
{           
throw new InvalidConfirmationCodeException;       
}
$user->confirmed = 1;       
$user->confirmation_code = null;       
$user->save();
       echo "";
       return view('welcome');   }
Thats all there is for email verification :)

Feel free to throw any query in comments :).


No comments:

Post a Comment