Laravel provides convenient methods for verifying email id of newly registered user but when it comes to REST APIs, Laravel doesn’t provided out of the box APIs for email verification.
So today I’m gonna show how to use the inbuilt Laravel email verification methods and notification template to build email verification APIs really fast.
If you would like to watch the example then you can check it out here:
Let’s start.
In your registration api, add sendEmailVerificationNotification on user after user is created.
User::create($request->getAttributes())->sendEmailVerificationNotification();
If you want to see the implementation of this function then you can find it here atIlluminate\Auth\MustVerifyEmail. This function is available in User model because it extendsAuthenticatable which usesIlluminate\Auth\MustVerifyEmail.
You can find the notification template here atIlluminate\Auth\Notifications\VerifyEmail
Define endpoints in api.php file.
Route::get('email/verify/{id}','VerificationController@verify')->name('verification.verify');// Make sure to keep this as your route nameRoute::get('email/resend','VerificationController@resend')->name('verification.resend');
Create this VerificationController using command:
php artisan make:controller VerificationController
Open VerificationController and define verify and resend function like this:
publicfunctionverify($user_id,Request$request){if(!$request->hasValidSignature()){returnresponse()->json(["msg"=>"Invalid/Expired url provided."],401);}$user=User::findOrFail($user_id);if(!$user->hasVerifiedEmail()){$user->markEmailAsVerified();}returnredirect()->to('/');}publicfunctionresend(){if(auth()->user()->hasVerifiedEmail()){returnresponse()->json(["msg"=>"Email already verified."],400);}auth()->user()->sendEmailVerificationNotification();returnresponse()->json(["msg"=>"Email verification link sent on your email id"]);}
Try this in postman and they should look something like this. Since i have defined some methods to keep the response consistent, So the response will be different.
If you want to make yourresponse consistent across application then you can watch the tutorials below.
You can find the entire codehere.
Hope you find it useful.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse