Laravel 10 - Newsletters

Touseef Afridi
12 Sep 24

Laravel 10 - Newsletters

In this tutorial, we will discuss how to implement a newsletter in Laravel 10. Newsletters helps automate email communication, keeping subscribers informed and engaged, improving audience reach and retention


If you're a video person, feel free to skip the post and check out the video instead!


Step # 1 : Create fresh Laravel project.

Two commands to create fresh Laravel project.
Global Command : laravel new newsletter
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist newsletter

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/newsletter
Next, install the required dependencies and run the Laravel Vite development server for front-end assets:
Command : npm install && npm run dev
In a new terminal window or tab (while keeping the Vite server running), navigate to the same project directory to execute further Laravel command.

Step # 3 : Install Newsletter package.

Command : composer require spatie/laravel-newsletter

Step # 4 : Publish the configuration.

Command : php artisan vendor:publish --tag="newsletter-config"
This will create a newsletter.php configuration file in the config directory.
Access the newsletter.php file and update it like following.
Update the driver from.
'driver' => env('NEWSLETTER_DRIVER', Spatie\Newsletter\Drivers\MailcoachDriver::class),
To
'driver' => env('NEWSLETTER_DRIVER', Spatie\Newsletter\Drivers\MailChimpDriver::class),
Update the endpoint from.
    'driver_arguments' => [
        'api_key' => env('NEWSLETTER_API_KEY'),
        'endpoint' => env('NEWSLETTER_ENDPOINT'),
    ],
To
    'driver_arguments' => [
        'api_key' => env('NEWSLETTER_API_KEY'),
        'endpoint' => env('NEWSLETTER_ENDPOINT', null),
    ],

Step # 5 : Install MailChimp package.

Command : composer require drewm/mailchimp-api
Next, you must provide values for the API key and list.subscribers.id. You'll find these values in the MailChimp UI.
Create MailChimp account.
Link : https://mailchimp.com/
Once done you will be redirected to Dashboard.
Let's get the API Key.
After logging in, click on your profile name in the top navigation bar and select Profile. Go to Extras and click on API keys. Click Create A Key to generate a new API key. Save the key securely, as you won’t be able to view it again.
Let's get the List ID.
From the left navigation menu, click on Audience and then All contacts. Click on Settings. Click on Audience name and defaults to find the Audience ID, which is your List ID.
Open your .env file and add the following environment variables and define the Key and ID.
NEWSLETTER_API_KEY="Your API Key Here"
NEWSLETTER_LIST_ID="Your List ID Here"

Step # 6 : Create a controller.

Run the following command to generate the NewsletterController.
Command : php artisan make:controller NewsletterController
Once the controller is created, replace the content of NewsletterController.php with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Newsletter;
class NewsletterController extends Controller
{
    // Displays the form view
    public function index()
    {
        return view('form');
    }
    // Handles the subscription process
    public function subscribe(Request $request)
    {
        // Validates email field
        $request->validate([
            'email' => 'required|email',
        ]);
        try {
            // Checks if the email is already subscribed to the newsletter
            if (Newsletter::isSubscribed($request->email)) {
                // Redirects back with an error message if the email is already subscribed
                return redirect()->back()->with('error', 'You have already subscribed to our Newsletters.');
            } else {
                // Subscribes the email to the newsletter
                Newsletter::subscribe($request->email);
                // Redirects back with a success message once subscribed
                return redirect()->back()->with('success', 'You have successfully subscribed to our Newsletters.');
            }
        } catch (Exception $e) {
            // If an error occurs, catch the exception and show the error message
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}

Step # 7 : Create & update route.

Import NewsletterController class.
use App\Http\Controllers\NewsletterController;
//Update the default route and create a new route to ask questions.
Route::get('/', [NewsletterController::class, 'index']);
Route::post('/subscribe', [NewsletterController::class, 'subscribe']);

Step # 8 : Create a view.

Create a view named form.blade.php and paste the following code.
<!DOCTYPE html>
<html>
<head>
 <title>Laravel Newsletter - Code Shotcut</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<body>
 <div class="container mt-5 bg-dark text-white">
  <div class="row">
   <div class="col-6 offset-3 mt-5 mb-5">
    <form action="{{ url('/subscribe') }}" method="post">
     @csrf
     <div class="form-group">
      <label for="exampleInputEmail1">SUBSCRIBE TO NEWSLETTER</label>
      <input type="email" name="email" class="form-control" placeholder="Enter email">
      <small id="emailHelp" class="form-text text-white">We'll never share your email with anyone else.</small>
      @if(session()->has('error'))
      <div class="alert alert-danger">
       {{ session()->get('error') }}
      </div>
      @endif
      @if(session()->has('success'))
      <div class="alert alert-success">
       {{ session()->get('success') }}
      </div>
      @endif
     </div>
     <button type="submit" class="btn btn-primary">Subscribe</button>
    </form>
   </div>
  </div>
 </div>
</body>
</html>

Step # 9 : It's time to test.

Start the Laravel development server.
Command : php artisan serve.
Access the URL below and start asking questions.
127.0.0.1:8000






Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering