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 at Illuminate\Auth\MustVerifyEmail. This function is available in User model because it extends Authenticatable which uses Illuminate\Auth\MustVerifyEmail.
You can find the notification template here at Illuminate\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 name
Route::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:
public function verify($user_id, Request $request) {
if (!$request->hasValidSignature()) {
return response()->json(["msg" => "Invalid/Expired url provided."], 401);
}
$user = User::findOrFail($user_id);
if (!$user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
}
return redirect()->to('/');
}
public function resend() {
if (auth()->user()->hasVerifiedEmail()) {
return response()->json(["msg" => "Email already verified."], 400);
}
auth()->user()->sendEmailVerificationNotification();
return response()->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 your response consistent across application then you can watch the tutorials below.
You can find the entire code here.
Hope you find it useful.
Top comments (0)