Verify email with code – PHP & MySQL

In this tutorial, we will learn how to verify email with code. When someone registers on your website, send him/her an email with a verification code and show a form to enter the code on your website. The user must enter the verification code in that form to verify his email. Only verified users will be allowed to log in.

Create users table

First, you need to create a “users” table in your database. Your table must have a “verification_code” field that will hold the code sent in the email. And the “email_verified_at” field tells the time the email was verified. This field will also be used to check if the user has verified his email or not.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` text NOT NULL,
  `email` text NOT NULL,
  `password` text NOT NULL,
  `verification_code` text NOT NULL,
  `email_verified_at` datetime DEFAULT NULL
);

User registration

Usually, the registration form has a name, email, and password field for the user.

<form method="POST">
    <input type="text" name="name" placeholder="Enter name" required />
    <input type="email" name="email" placeholder="Enter email" required />
    <input type="password" name="password" placeholder="Enter password" required />

    <input type="submit" name="register" value="Register">
</form>

When this form submits, we need to generate a verification code and send it to the user. To send an email, we are going to use a library called “PHPMailer”. Make sure you have “composer” downloaded and installed in your system. Run the following command at the root of your project:

composer require phpmailer/phpmailer

You can also download and include the PHPMailer library manually from Github. The following code will send a verification code to the user’s email address and save the user’s data in the database:

<?php
    //Import PHPMailer classes into the global namespace
    //These must be at the top of your script, not inside a function
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;

    //Load Composer's autoloader
    require 'vendor/autoload.php';

    if (isset($_POST["register"]))
    {
        $name = $_POST["name"];
        $email = $_POST["email"];
        $password = $_POST["password"];

        //Instantiation and passing `true` enables exceptions
        $mail = new PHPMailer(true);

        try {
            //Enable verbose debug output
            $mail->SMTPDebug = 0;//SMTP::DEBUG_SERVER;

            //Send using SMTP
            $mail->isSMTP();

            //Set the SMTP server to send through
            $mail->Host = 'smtp.gmail.com';

            //Enable SMTP authentication
            $mail->SMTPAuth = true;

            //SMTP username
            $mail->Username = 'your_email@gmail.com';

            //SMTP password
            $mail->Password = 'your_password';

            //Enable TLS encryption;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

            //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            $mail->Port = 587;

            //Recipients
            $mail->setFrom('your_email@gmail.com', 'your_website_name');

            //Add a recipient
            $mail->addAddress($email, $name);

            //Set email format to HTML
            $mail->isHTML(true);

            $verification_code = substr(number_format(time() * rand(), 0, '', ''), 0, 6);

            $mail->Subject = 'Email verification';
            $mail->Body    = '<p>Your verification code is: <b style="font-size: 30px;">' . $verification_code . '</b></p>';

            $mail->send();
            // echo 'Message has been sent';

            $encrypted_password = password_hash($password, PASSWORD_DEFAULT);

            // connect with database
            $conn = mysqli_connect("localhost:8889", "root", "root", "test");

            // insert in users table
            $sql = "INSERT INTO users(name, email, password, verification_code, email_verified_at) VALUES ('" . $name . "', '" . $email . "', '" . $encrypted_password . "', '" . $verification_code . "', NULL)";
            mysqli_query($conn, $sql);

            header("Location: email-verification.php?email=" . $email);
            exit();
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }
    }
?>

User login

When users try to log in, we must check if the user’s email is verified or not. Usually, login form has 2 fields, email, and password:

<form method="POST">
    <input type="email" name="email" placeholder="Enter email" required />
    <input type="password" name="password" placeholder="Enter password" required />

    <input type="submit" name="login" value="Login">
</form>

When this form submits, we will check if the user’s credentials are okay. And also if his/her email is verified.

<?php
    
    if (isset($_POST["login"]))
    {
        $email = $_POST["email"];
        $password = $_POST["password"];

        // connect with database
        $conn = mysqli_connect("localhost:8889", "root", "root", "test");

        // check if credentials are okay, and email is verified
        $sql = "SELECT * FROM users WHERE email = '" . $email . "'";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) == 0)
        {
            die("Email not found.");
        }

        $user = mysqli_fetch_object($result);

        if (!password_verify($password, $user->password))
        {
            die("Password is not correct");
        }

        if ($user->email_verified_at == null)
        {
            die("Please verify your email <a href='email-verification.php?email=" . $email . "'>from here</a>");
        }

        echo "<p>Your login logic here</p>";
        exit();
    }
?>

Email verification

Create a file named “email-verification.php” and create a hidden input field for email and a text field for verification code:

<form method="POST">
    <input type="hidden" name="email" value="<?php echo $_GET['email']; ?>" required>
    <input type="text" name="verification_code" placeholder="Enter verification code" required />

    <input type="submit" name="verify_email" value="Verify Email">
</form>

When this form submits, we will check if the verification code matches the one in the database. If the code does not match then it will show an error, otherwise, it will mark the user as verified.

<?php

    if (isset($_POST["verify_email"]))
    {
        $email = $_POST["email"];
        $verification_code = $_POST["verification_code"];

        // connect with database
        $conn = mysqli_connect("localhost:8889", "root", "root", "test");

        // mark email as verified
        $sql = "UPDATE users SET email_verified_at = NOW() WHERE email = '" . $email . "' AND verification_code = '" . $verification_code . "'";
        $result  = mysqli_query($conn, $sql);

        if (mysqli_affected_rows($conn) == 0)
        {
            die("Verification code failed.");
        }

        echo "<p>You can login now.</p>";
        exit();
    }

?>

Conclusion

Adding this feature to your website helps you to separate real and fake email addresses in your database. It will greatly help you in your marketing and you will be satisfied that your emails are going to real email accounts. If you want to know if your email is being read by the receiver or not, please follow this.

Convert date format to another – PHP, HTML

In this tutorial, we are going to teach you how to convert the date format from one to another using Javascript. We will also be adding, subtracting date by days.

Video tutorial

First, we will create a form to get the source and destination format from the user.

<form method="POST" onsubmit="return generateCode(this);">
    
    <div>
        <select name="source_format">
            <option value="">Enter source format</option>
            <option value="timestamp">Timestamp (123456789)</option>
            <option value="Y-m-d">Y-m-d (2020-08-30)</option>
            <option value="Y-m-d H:i:s">Y-m-d H:i:s (2020-08-30 14:30:18)</option>
            <option value="Y-m-d h:i:s A">Y-m-d h:i:s A (2020-08-30 02:30:18 PM)</option>
            <option value="Y-m-d h:i:s a">Y-m-d h:i:s a (2020-08-30 02:30:18 pm)</option>
            <option value="d M, Y">d M, Y (30 August, 2020)</option>
            <option value="D">D (Mon, Tue)</option>
        </select>
    </div>

    <div style="margin-top: 10px;">
        <select name="destination_format">
            <option value="">Enter destination format</option>
            <option value="timestamp">Timestamp (123456789)</option>
            <option value="Y-m-d">Y-m-d (2020-08-30)</option>
            <option value="Y-m-d H:i:s">Y-m-d H:i:s (2020-08-30 14:30:18)</option>
            <option value="Y-m-d h:i:s A">Y-m-d h:i:s A (2020-08-30 02:30:18 PM)</option>
            <option value="Y-m-d h:i:s a">Y-m-d h:i:s a (2020-08-30 02:30:18 pm)</option>
            <option value="d M, Y">d M, Y (30 August, 2020)</option>
            <option value="D">D (Mon, Tue)</option>
        </select>
    </div>

    <input type="submit" value="Generate Code" />

    <p id="output" style="display: none;"></p>
</form>

Then we will create a Javascript function that will write the PHP code to echo the date by converting it from source format to destination format.

<script>
    function generateCode(form) {

        var sourceFormat = form.source_format.value;
        var destinationFormat = form.destination_format.value;

        var html = "";
        var dateHtml = "";
        if (sourceFormat == "timestamp" && destinationFormat == "timestamp") {
            dateHtml = `echo $timestamp_value;`;
        } else if (sourceFormat == "timestamp") {
            dateHtml = `echo date('` + destinationFormat + `', $timestamp_value);`;
        } else if (destinationFormat == "timestamp") {
            dateHtml = `echo strtotime($date_value);`;
        } else {
            dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value));`;
        }
        html += `&lt;?php<br />
            <span style='margin-left: 1em;'>&emsp;` + dateHtml + `</span><br />
        ?>`;
        
        document.getElementById("output").innerHTML = html;
        document.getElementById("output").style.display = '';

        return false;
    }
</script>

The resulting output will be displayed in a paragraph. Right now we are displaying a dropdown to select a date format. But what if the user wants to write a custom format ? So we will create 2 more fields for writing custom format for source and destination.

<input type="text" style="margin-left: 10px;" name="source_format_custom" placeholder="Custom source format" />

<input type="text" style="margin-left: 10px;" name="destination_format_custom" placeholder="Custom destination format" />

Then we need to update our custom date format variables if these fields have some value.

var sourceFormat_custom = form.source_format_custom.value;
if (sourceFormat_custom != "") {
    sourceFormat = sourceFormat_custom;
}

var destinationFormat_custom = form.destination_format_custom.value;
if (destinationFormat_custom != "") {
    destinationFormat = destinationFormat_custom;
}

Add/subtract from the date

Now we need to add or subtract months, years, or days from the new date format. For this, we will create 2 dropdowns to check if the user wants to add or subtract. And second to check if he wants to add/subtract days, months, or years.

<p style="text-align: center;">Add / subtract date (optional)</p>

<div>
    <select name="addsubtract_date">
        <option value="">None</option>
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
    </select>

    <select name="addsubtract_datetype">
        <option value="years">Years</option>
        <option value="months">Months</option>
        <option value="days">Days</option>
        <option value="hours">Hours</option>
        <option value="minutes">Minutes</option>
        <option value="seconds">Seconds</option>
    </select>
</div>

<input type="number" placeholder="Enter value" name="addsubtract_datevalue" />

Now when the form is submitted, we need to get the values of both these dropdowns.

var addsubtractdate = "";
if (form.addsubtract_date.value == "add") {
    addsubtractdate = "'+ " + form.addsubtract_datevalue.value + " " + form.addsubtract_datetype.value + "'";
} else if (form.addsubtract_date.value == "subtract") {
    addsubtractdate = "'- " + form.addsubtract_datevalue.value + " " + form.addsubtract_datetype.value + "'";
}

After that, we need to make changes in every echo statement in our Javascript code to handle this add/subtract feature.

if (sourceFormat == "timestamp" && destinationFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo $timestamp_value;`;
    } else {
        dateHtml = `echo strtotime(` + addsubtractdate + `, $timestamp_value);`;
    }
} else if (sourceFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo date('` + destinationFormat + `', $timestamp_value);`;
    } else {
        dateHtml = `echo date('` + destinationFormat + `', strtotime(` + addsubtractdate + `, $timestamp_value));`;
    }
} else if (destinationFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo strtotime($date_value);`;
    } else {
        dateHtml = `echo strtotime(` + addsubtractdate + `, strtotime($date_value));`;
    }
} else {
    if (addsubtractdate == "") {
        dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value));`;
    } else {
        dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value . ` + addsubtractdate + `));`;
    }
}

You can run the script now, and you will be able to generate the code for converting the date from one format to another. Moreover, you can also get the code for adding/subtracting days, months, or years from the resultant date. That’s how you can convert date format from one to another.

Learn how to calculate the time passed since the date in PHP and Javascript.

Calculate time passed since date – Javascript, PHP

Feel free to download the source code below.

[wpdm_package id=’1183′]

Prevent file access from URL – PHP htaccess

When developing a web application, it is very important for you to prevent file access from URL for the users. Because someone might try to download all your images and videos by directly accessing them from the URL. You must allow users to view the images and videos directly from your website instead of just letting the automated scripts download all uploaded data.

.htaccess

First, you need to create a file named “.htaccess” along with the dot “.” without the double quotes at the root folder of your project. Some operating systems hide the files that start with a dot extension.

  • In Windows, go to “view” from the top menu and check the “show hidden items” checkbox.
  • In Mac, press (command + shift + dot) (⌘ + ⇧ + .) at the same time.
  • In Ubuntu, press Ctrl + H.

Following should be the content of your .htaccess file:

# enable mod_rewrite
RewriteEngine On

# RewriteCond = define rule condition
# HTTP_REFERER = check from where the request originated
# ! = exclude
# ^ = start of string
# [NC] = case insensitive search
RewriteCond %{HTTP_REFERER} !^http://localhost:8888/tutorials/video-streaming-php [NC]

# \ = match any
# . = any character
# () = pattern, group
# $ = end of string

# [F] = forbidden, 403
# [L] = stop processing further rules
RewriteRule \.(gif|jpg|jpeg|png|mp4|mov|mkv|flv)$ - [F,L]

At line #9, you must place your website base URL without forwarding the slash “/” at the end. Using htaccess, you can also prevent “.env” files from accessing in your Laravel application. Follow this for more.

Access from code only

Now if you try to access the file directly from the URL, you will get a 403 Forbidden error. But you can easily access it from your code like this:

<video src="video.mp4" controls></video>

This prevent file access from the URL but you can still see it in the browser. However, the user can still manually download the video file. But it prevents the automated scripts to download all the files from your server directory.

Detect multiple tabs opened at the same time – Javascript

If you have used WhatsApp Web, you may encounter a situation where if you open the web.whatsapp.com in multiple tabs in the same browser, you will get the error that “it is already being opened in another tab”. So in this article, we are going to teach you how you can detect multiple tabs opened at the same time using vanilla Javascript.

This is done for various reasons, top of the most is security. So how you can add this feature to your website ? The following code will display an alert message if a 2nd tab is opened at the same time:

<script>
    // Broadcast that you're opening a page.
    localStorage.openpages = Date.now();
    window.addEventListener('storage', function (e) {
        if(e.key == "openpages") {
            // Listen if anybody else is opening the same page!
            localStorage.page_available = Date.now();
        }
        if(e.key == "page_available") {
            alert("One more page already open");
        }
    }, false);
</script>

window.addEventListener(‘storage’, function (e) {});” This listener will be called only when the local storage value is updated from an external source, which means the other tab has made any changes in the local storage.

[do_widget id=custom_html-4]

How it works:

You might need to read the following steps 2 or 3 times to grab the concept properly.

  1. When you open the 1st tab, line # 3 will create a local storage value named “openpages”.
  2. Storage listener will NOT be called because the local storage value is updated from this tab.
  3. When you open the second tab, line # 3 will also create a local storage value named “openpages”.
  4. Storage listener from the 1st tab will be called because the local storage is updated from the 2nd tab.
  5. 1st tab will receive the value of “e.key” as “openpages”.
  6. So it will create another local storage value “page_available” at line # 7.
  7. Now this will call the storage listener from the 2nd tab. Because for the 2nd tab, it is called from the 1st tab.
  8. 2nd tab will receive the value of “e.key” as “page_available”, so it will display an alert message.

That’s how you can detect multiple tabs opened by the user at the same time. Let me know if you have any problem understanding this.

How to check if email is read by user – PHP, Gmail, Outlook

Problem:

If you are developing a web project that includes sending emails to users, then it is very important for you to know if those emails are being read or delivered to those users. For example, if you are sending marketing emails to your subscriber’s list, then it is essential for you to know that your email is read by which users. And by which users the email is not read yet.

This will greatly help you to make decisions if you are sending the right emails or not. Because if the user can read your marketing email, but didn’t buy anything from you, it clearly means there was something wrong with the email. But how do you know if the email sent from PHP, Laravel, or whatever framework you are using, is being opened by the user?

Solution:

Follow this tutorial, and you will be able to add such functionality in your web project.

Sending the email:

For sending the email, you can use the popular “PHPMailer” library. You can also use built-in PHP “mail()” function. Open command prompt or Terminal in your project root folder and run the following command (make sure you have composer installed in your system):

composer require phpmailer/phpmailer

This will create a “vendor” folder in your project root folder. Create a table in your MySQL database named “emails” and it will have 4 columns:

  1. ID (INTEGER) (primary key, auto_increment, not null)
  2. email (TEXT) (not null)
  3. content (TEXT) (not null)
  4. read_at (DATETIME) (null)
How to check if email is read by user - PHP, Gmail, Outlook - Emails table
How to check if email is read by user – PHP, Gmail, Outlook – Emails table

Send email using the following code in your PHP file:

<?php

// import PHPMailer classes into the global namespace
// these must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// load Composer's autoloader
require 'vendor/autoload.php';

// instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

// the person who will receive the email
$recipient = "recipient_email";

// content of email
$content = "This is the HTML message body <b>in bold!</b>";

// connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "test");

// insert in mails table
$sql = "INSERT INTO emails (email, content) VALUES ('" . $recipient . "', '" . $content . "')";
mysqli_query($conn, $sql);

// get inserted mail ID
$email_id = mysqli_insert_id($conn);

// append empty image tag with email content
// this will help to know when user read that email
$base_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$content .= "<img src='" . $base_url . "email_read.php?email_id=" . $email_id . "' style='display: none;' />";

try {
    // disable verbose debug output
    $mail->SMTPDebug = 0;

    // send using SMTP
    $mail->isSMTP();

    // set the SMTP server to send through
    $mail->Host = 'smtp.gmail.com';

    // enable SMTP authentication
    $mail->SMTPAuth = true;

    // SMTP username
    $mail->Username = 'your_email@gmail.com';

    // SMTP password
    $mail->Password = 'your_password';

    // enable TLS encryption
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
    $mail->Port = 587;

    $mail->setFrom('your_email@gmail.com', 'Your name');

    // add a recipient
    $mail->addAddress($recipient);

    // set email format to HTML
    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body = $content;

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

You just need to change the email and password with your Gmail address and password. To learn more about configuring an SMTP server, read this.

[do_widget id=custom_html-4]

This is how the email will be received in the user’s inbox (image will not be visible):

A sample mail
How to check if email is read by user – PHP, Gmail, Outlook – Inbox

View emails and time they are read:

Now, we will create a separate page for the admin where he/she can see a list of all emails sent from the website along with the time they are read by the user. Create a file named “view_emails.php” and paste the following code in it:

<?php

// connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "test");

// get all emails
$sql = "SELECT * FROM emails";
$result = mysqli_query($conn, $sql);

?>

<!-- basic style of table -->
<style>
    table, td {
        border: 1px solid black;
        border-collapse: collapse;
        padding: 25px;
    }
</style>

<table>

    <?php

    // show all emails
    while ($row = mysqli_fetch_object($result))
    {
        ?>
        <tr>
            <td><?= $row->id; ?></td>
            <td><?= $row->email; ?></td>
            <td><?= $row->content; ?></td>
            <td><?= $row->read_at == null ? "Not read" : $row->read_at; ?></td>
        </tr>
        <?php
    }

    ?>

</table>

Access this page directly and you will see a list of all emails with the time they are read (next step).

How to check if email is read by user - PHP, Gmail, Outlook - Not read
How to check if email is read by user – PHP, Gmail, Outlook – Not read

Mark the time when email is read:

Create a file named “email_read.php” and paste the following code in it:

<?php

// this page will be executed only when the email is opened by user

// connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "test");

// get email ID
$email_id = $_GET["email_id"];

// update read_at value in emails table
$sql = "UPDATE emails SET read_at = NOW() WHERE id = '" . $email_id . "'";
mysqli_query($conn, $sql);

[do_widget id=custom_html-4]

You will never see the output from this file but it will mark the time in database when the email is read.

How to check if email is read by user – PHP, Gmail, Outlook – Read

Let me know if you had any problem in following this tutorial.

[wpdm_package id=’1170′]

Preview Laravel email before sending – PHP, AJAX

Either you are sending an email in Laravel via normal form POST request or via AJAX. This tutorial will help you add functionality where you can preview Laravel email before sending it. If you are adding functionality to your Laravel project where you need to send an email, it is very important during the development to check the preview of mail before sending.

Normally, when you receive the email in your inbox, you can see how it will look to users. But if you haven’t set up your SMTP server for sending emails, then following this tutorial will save you a lot of time during development.

Create a new Laravel project

To create a new Laravel project, open your command prompt or Terminal and run the following command in it:

composer create-project laravel/laravel example-app

This will create a folder named “example-app”. Now, you need to enter this folder using the following command:

cd example-app

When your Terminal is inside this folder, run the following command to start the server:

php artisan serve

Typically, this starts your project at host 127.0.0.1 and port 8000. So you can access it from the URL:

http://127.0.0.1:8000

Create controller and mailer

Create a new controller using the following command, you can also use your own controller if you want:

php artisan make:controller UserController

Now, open your “routes/web.php” file and create a new route:

// include controller
use App\Http\Controllers\UserController;

// create route
Route::get("/send-mail", [UserController::class, "send_mail"]);

Create a mailer to send mails by running the following command in your Terminal:

php artisan make:mail SendMail

Now, we need to create the following function in “App\Http\Controllers\UserController”:

use Mail;
use App\Mail\SendMail;

class UserController extends Controller
{
    // create method
    public function send_mail()
    {
        // send email
        // preview with dynamic variable data

        $data = "This is a variable.";

        // pass as a parameter
        $mailable = new SendMail($data);
        // Mail::to("recipient@gmail.com")->send($mailable);

        // preview email
        return $mailable->render();
    }
}

Following will be the content of your “App\Mail\SendMail”. You can add all the variables you want to pass in this mailer:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;

    // class data member
    public $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    // parametrized constructor
    public function __construct($data)
    {
        // assign value
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // create this folder mails
        // and file test.blade.php

        // pass value in view
        return $this->view('mails/test', [
            "data" => $this->data
        ]);
    }
}

At line #40, we need to create a new file in views folder, “resources/views/mails/test.blade.php” and in this file you can write the content of your email. For the sake of understanding, I am writing simple text with variables:

<h1>This is mail:</h1>

<!-- display in mail view -->
Data = {{ $data }}

If you access your browser at “http://127.0.0.1:8000/send-mail”, you will see the content of email with all variables rendered on it.

Preview email from AJAX

If you are sending an email via an AJAX request, then it might be difficult for you during the development to check how the email will look like. You might be sending an email on each test and viewing it from your Gmail inbox to preview the email. But there is a shorter method to do that, and it will surely save your time.

First, create a new route that will render a view file.

// routes/web.php
Route::get("/send-mail-ajax", function () {
    // render view
    return view("send_mail_ajax");
});

Create a file named “send_mail_ajax.blade.php” inside the “resources/views” folder and paste the following code into it:

<!-- meta tag for CSRF token -->
<meta name="_token" content="{{ csrf_token() }}">

<!-- hidden input field for base url -->
<input type="hidden" id="base_url" value="{{ url('/') }}" />

<!-- send ajax -->
<script>
    var ajax = new XMLHttpRequest();
    ajax.open("POST", document.getElementById("base_url").value + "/send-mail-ajax", true);

    // when the response is received
    ajax.onreadystatechange = function () {
        if (this.readyState == 4) {
            if (this.status == 200) {
                // display in browser
                document.write(this.responseText);
            }

            // handler error
            if (this.status == 500) {
                console.log(this.responseText);
            }
        }
    };

    var formData = new FormData();
    formData.append("_token", document.querySelector("meta[name=_token]").content);
    ajax.send(formData);
</script>

We have created a meta tag for saving CSRF token which is required for each POST request in Laravel, and a hidden input field that will save the website’s base URL. Then we are sending an AJAX request, and when the response is successfully received then we are displaying that in current web page.

Don’t worry, it will be used just during the development process. Once it is reviewed, then you can comment out that code at line #17.

Create a POST route in “routes/web.php” and it will use the same method in UserController, only the method is set to POST:

// create route
Route::post("/send-mail-ajax", [UserController::class, "send_mail"]);

Try to access the URL at “http://127.0.0.1:8000/send-mail-ajax”, you will first view an empty page then after few seconds, you will see the content of email in your web page.

Let me know if you need any help in following this tutorial.

[wpdm_package id=’1171′]

Laravel Blog (Website + Android app) with Admin Panel

A Laravel blog website along with an Android app is created with an admin panel. It uses the design template from https://bootstrapmade.com/. It has the following key features:

Google Adsense approved

The project is tested with Google Adsense and it was approved by Google for monetization. You just have to link with your Google account and you will start receiving money once you reach the Google payment threshold.

User side

  1. 70 built-in blog posts.
  2. Random quotations.
  3. Total users display.
  4. Custom advertisement to generate revenue.
  5. Share posts on Twitter and Facebook.
  6. Limit access to some features for registered users only.
  7. Registration with Email Verification.
  8. Secure Login.
  9. Comment on Post.
  10. Reply to the comment.
  11. Related Posts.
  12. Subscribe to the newsletter.
  13. Social Links.
  14. A section to sell items directly.
  15. Amazon affiliate links.
  16. Realtime Chat with admin (Firebase).
  17. Manage Profile.
  18. Change Password.
  19. Custom Advertisement.

Admin panel

  1. Dashboard Statistics.
  2. Add/Edit blog posts.
  3. Add/Edit items that sell directly.
  4. Manage Inbox.
  5. Manage Comments.
  6. Realtime Chat with users (Firebase).

Android app

We also developed an Android App for this project which your users can download from Google Play Store and read your blog posts from that app. Here is the demo of the Laravel blog android app:

Our TrustPilot reviews

TrustPilot-reviews
TrustPilot-reviews