Manage newsletters in Laravel

Last update: Jun 21, 2022

Manage newsletters in Laravel

Latest Version MIT Licensed GitHub Workflow Status Check & fix styling Total Downloads

This package provides an easy way to integrate MailChimp with Laravel.

Should you find that Mailchimp is too expensive for your use case, consider using Mailcoach instead. Mailcoach is a premium Laravel package that allows you to self host your email lists and campaigns.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install this package via composer using:

composer require spatie/laravel-newsletter

The package will automatically register itself.

To publish the config file to config/newsletter.php run:

php artisan vendor:publish --provider="Spatie\Newsletter\NewsletterServiceProvider"

This will publish a file newsletter.php in your config directory with the following contents:

return [

    /*
     * The driver to use to interact with MailChimp API.
     * You may use "log" or "null" to prevent calling the
     * API directly from your environment.
     */
    'driver' => env('MAILCHIMP_DRIVER', 'api'),

    /*
     * The API key of a MailChimp account. You can find yours at
     * https://us10.admin.mailchimp.com/account/api-key-popup/.
     */
    'apiKey' => env('MAILCHIMP_APIKEY'),

    /*
     * The listName to use when no listName has been specified in a method.
     */
    'defaultListName' => 'subscribers',

    /*
     * Here you can define properties of the lists.
     */
    'lists' => [

        /*
         * This key is used to identify this list. It can be used
         * as the listName parameter provided in the various methods.
         *
         * You can set it to any string you want and you can add
         * as many lists as you want.
         */
        'subscribers' => [

            /*
             * A MailChimp list id. Check the MailChimp docs if you don't know
             * how to get this value:
             * http://kb.mailchimp.com/lists/managing-subscribers/find-your-list-id.
             */
            'id' => env('MAILCHIMP_LIST_ID'),
        ],
    ],

    /*
     * If you're having trouble with https connections, set this to false.
     */
    'ssl' => true,
];

Usage

Behind the scenes v3 for the MailChimp API is used.

After you've installed the package and filled in the values in the config-file working with this package will be a breeze. All the following examples use the facade. Don't forget to import it at the top of your file.

use Newsletter;

Subscribing, updating and unsubscribing

Subscribing an email address can be done like this:

use Newsletter;

Newsletter::subscribe('[email protected]');

Let's unsubscribe someone:

Newsletter::unsubscribe('[email protected]');

You can pass some merge variables as the second argument:

Newsletter::subscribe('[email protected]', ['FNAME'=>'Rince', 'LNAME'=>'Wind']);

Please note the at the time of this writing the default merge variables in MailChimp are named FNAME and LNAME. In our examples we use firstName and lastName for extra readability.

You can subscribe someone to a specific list by using the third argument:

Newsletter::subscribe('[email protected]', ['FNAME'=>'Rince', 'LNAME'=>'Wind'], 'subscribers');

That third argument is the name of a list you configured in the config file.

You can also subscribe and/or update someone. The person will be subscribed or updated if he/she is already subscribed:

Newsletter::subscribeOrUpdate('[email protected]', ['FNAME'=>'Foo', 'LNAME'=>'Bar']);

You can subscribe someone to one or more specific group(s)/interest(s) by using the fourth argument:

Newsletter::subscribeOrUpdate('[email protected]', ['FNAME'=>'Rince','LNAME'=>'Wind'], 'subscribers', ['interests'=>['interestId'=>true, 'interestId'=>true]])

Simply add false if you want to remove someone from a group/interest.

You can also unsubscribe someone from a specific list:

Newsletter::unsubscribe('[email protected]', 'subscribers');

Deleting subscribers

Deleting is not the same as unsubscribing. Unlike unsubscribing, deleting a member will result in the loss of all history (add/opt-in/edits) as well as removing them from the list. In most cases you want to use unsubscribe instead of delete.

Here's how to perform a delete:

Newsletter::delete('[email protected]');

Deleting subscribers permanently

Delete all personally identifiable information related to a list member, and remove them from a list. This will make it impossible to re-import the list member.

Here's how to perform a permanent delete:

Newsletter::deletePermanently('[email protected]');

Getting subscriber info

You can get information on a subscriber by using the getMember function:

Newsletter::getMember('[email protected]');

This will return an array with information on the subscriber. If there's no one subscribed with that e-mail address the function will return false

There's also a convenience method to check if someone is already subscribed:

Newsletter::hasMember('[email protected]'); //returns a boolean

In addition to this you can also check if a user is subscribed to your list:

Newsletter::isSubscribed('[email protected]'); //returns a boolean

Creating a campaign

This the signature of createCampaign:

public function createCampaign(
    string $fromName,
    string $replyTo,
    string $subject,
    string $html = '',
    string $listName = '',
    array $options = [],
    array $contentOptions = [])

Note the campaign will only be created, no emails will be sent out.

Handling errors

If something went wrong you can get the last error with:

Newsletter::getLastError();

If you just want to make sure if the last action succeeded you can use:

Newsletter::lastActionSucceeded(); //returns a boolean

Need something else?

If you need more functionality you get an instance of the underlying MailChimp Api with:

$api = Newsletter::getApi();

Testing

Run the tests with:

vendor/bin/phpunit

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

GitHub

https://github.com/spatie/laravel-newsletter
Comments
  • 1. 400: The resource submitted could not be validated. For field-specific details, see the 'errors' array.

    Did I miss something in installation or else. I can't figure out the problem.

    400: The resource submitted could not be validated. For field-specific details, see the 'errors' array.

    Reviewed by flyingcoder at 2016-09-05 01:36
  • 2. Resubscribing not working

    First of all, thanks for the package :)

    In regards to the issue probably it's just me so apologies in advance!

    Calling subscribe() on an email that's already in the list but is marked as Unsubscribed does nothing for me. So the walk-around I am using right now is to first call delete(), and then subscribe(), and that's perfectly working. The only issue I am having with this walk-around is I lose track of when the user was added on the list for the first time.

    Am I missing something? Or if not, would you consider merging a PR by me which adds that functionality?

    Reviewed by andonovn at 2018-07-21 12:43
  • 3. Non-static method Spatie\Newsletter\MailChimp\Newsletter::subscribe() should not be called statically

    Hi,

    I've recently upgraded to Laravel 5.2 and I've noticed the following errors appearing.

    Non-static method Spatie\Newsletter\MailChimp\Newsletter::subscribe() should not be called statically

    I'm referencing the Newsletter with the following at the top of my controller:

    use Spatie\Newsletter\MailChimp\Newsletter;

    And it was working ok previously. Are the methods no longer defined as static? Any idea what could be causing this? Many thanks for your help

    Reviewed by danmurf at 2016-02-24 13:20
  • 4. Subscribe method response return false everytime

    fail to insert email in list getting response false in my Newsletter.php when i output dd($this->mailChimp->getLastResponse()); It gives below Result Please have look once

    array:3 [▼ "headers" => array:26 [▼ "url" => "https://us16.api.mailchimp.com/3.0/lists/47108f58ef/members" "content_type" => null "http_code" => 0 "header_size" => 0 "request_size" => 0 "filetime" => -1 "ssl_verify_result" => 1 "redirect_count" => 0 "total_time" => 0.953 "namelookup_time" => 0.515 "connect_time" => 0.734 "pretransfer_time" => 0.0 "size_upload" => 0.0 "size_download" => 0.0 "speed_download" => 0.0 "speed_upload" => 0.0 "download_content_length" => -1.0 "upload_content_length" => -1.0 "starttransfer_time" => 0.0 "redirect_time" => 0.0 "redirect_url" => "" "primary_ip" => "104.88.193.117" "certinfo" => [] "primary_port" => 443 "local_ip" => "192.168.10.4" "local_port" => 61442 ] "httpHeaders" => null "body" => null ]

    My controller method is as

    public function store(Request $request)
        {
    
            Newsletter::subscribe('[email protected]');
    
            Session::flash('subscribed', 'Successfully subscribed.');
            return redirect()->back();
        }
    

    Even i am not getting any Error Please Help to fix

    I also Post This Question on stackoverflow but no response https://stackoverflow.com/questions/44911181/unable-to-connect-laravel-to-mailchimp-laravel-5-4

    Reviewed by ramzan07 at 2017-07-04 19:45
  • 5. Invalid MailChimp API key supplied

    freshly installed and newly created list is giving me there is nothing in my mailchimp column

    Whoops, looks like something went wrong.

    1/1 Exception in MailChimp.php line 39: Invalid MailChimp API key supplied.

    Reviewed by maximusblade at 2016-06-09 15:27
  • 6. Newsletter::subscribe Unknown error, call getLastResponse() to find out what happened. error

    @freekmurze thanks for the package

    I am getting error while trying to subscribe an email Unknown error, call getLastResponse() to find out what happened.

    When I try to call getLastResponse() it throws error Call to undefined method Spatie\Newsletter\Newsletter::getLastResponse()

    Below is my controllers function and I've checked that $email is coming correctly:

       public function newsletterSubscription(Request $request) {
            $email = $request->get('email');
            Newsletter::subscribe($email);
            if (Newsletter::lastActionSucceeded()){
               return Redirect::back(); 
            }
            return Newsletter::getLastError();
        }
    

    Please help!

    Reviewed by luan0508 at 2016-10-07 17:07
  • 7. Trying to get property of non-object

    After following the instructions, I'm stuck with this error

    ErrorException in NewsletterList.php line 37: Trying to get property of non-object I'm using Laravel 5.1.9

    Thank you!

    This is my main controller:

    handleError('8', 'Trying to get property of non-object', '/home/vagrant/Code/jobnow/vendor/spatie/laravel-newsletter/src/MailChimp/NewsletterList.php', '37', array('email' => '[email protected]', 'mergeVars' => array(), 'listName' => '', 'listProperties' => array('id' => 'XXXXXXXXXX', 'createCampaign' => array('fromEmail' => '', 'fromName' => '', 'toName' => ''), 'subscribe' => array('emailType' => 'html', 'requireDoubleOptin' => false, 'updateExistingUser' => false), 'unsubscribe' => array('deletePermanently' => false, 'sendGoodbyeEmail' => false, 'sendUnsubscribeEmail' => false)), 'emailType' => 'html', 'requireDoubleOptin' => false, 'updateExistingUser' => false)) in NewsletterList.php line 37 at NewsletterList->subscribe('[email protected]', array(), '') in Newsletter.php line 49 at Newsletter->subscribe('[email protected]') in Facade.php line 210 at Facade::__callStatic('subscribe', array('[email protected]')) in mainController.php line 9 at NewsletterFacade::subscribe('[email protected]') in mainController.php line 9 at mainController->index() at call_user_func_array(array(object(mainController), 'index'), array()) in Controller.php line 256 at Controller->callAction('index', array()) in ControllerDispatcher.php line 164 at ControllerDispatcher->call(object(mainController), object(Route), 'index') in ControllerDispatcher.php line 112 at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103 at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114 at ControllerDispatcher->callWithinStack(object(mainController), object(Route), object(Request), 'index') in ControllerDispatcher.php line 69 at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\mainController', 'index') in Route.php line 201 at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134 at Route->run(object(Request)) in Router.php line 704 at Router->Illuminate\Routing\{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103 at Pipeline->then(object(Closure)) in Router.php line 706 at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 671 at Router->dispatchToRoute(object(Request)) in Router.php line 631 at Router->dispatch(object(Request)) in Kernel.php line 236 at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50 at VerifyCsrfToken->handle(object(Request), object(Closure)) at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 54 at ShareErrorsFromSession->handle(object(Request), object(Closure)) at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62 at StartSession->handle(object(Request), object(Closure)) at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37 at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59 at EncryptCookies->handle(object(Request), object(Closure)) at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42 at CheckForMaintenanceMode->handle(object(Request), object(Closure)) at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103 at Pipeline->then(object(Closure)) in Kernel.php line 122 at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87 at Kernel->handle(object(Request)) in index.php line 54 ```
    Reviewed by taytus at 2015-08-11 05:08
  • 8. Can't install with laravel/framework v5.7.*

    Not really ready to upgrade Laravel yet, but wanted to add newsletter. Which version should be compatible with laravel/framework v5.7.*? (if that's the problem here)

    composer require spatie/laravel-newsletter
    
    
    Using version ^4.4 for spatie/laravel-newsletter
    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Installation request for spatie/laravel-newsletter ^4.4 -> satisfiable by spatie/laravel-newsletter[4.4.0].
        - Conclusion: remove laravel/framework v5.7.28
        - Conclusion: don't install laravel/framework v5.7.28
        - spatie/laravel-newsletter 4.4.0 requires illuminate/support ~5.8.0 -> satisfiable by illuminate/support[5.8.x-dev, v5.8.0, v5.8.11, v5.8.12, v5.8.14, v5.8.2, v5.8.3, v5.8.4, v5.8.8, v5.8.9], laravel/framework[5.8.x-dev].
        - don't install illuminate/support 5.8.x-dev|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.0|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.11|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.12|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.14|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.2|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.3|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.4|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.8|don't install laravel/framework v5.7.28
        - don't install illuminate/support v5.8.9|don't install laravel/framework v5.7.28
        - Can only install one of: laravel/framework[5.8.x-dev, v5.7.28].
        - Installation request for laravel/framework (locked at v5.7.28, required as 5.7.*) -> satisfiable by laravel/framework[v5.7.28].
    
    
    Installation failed, reverting ./composer.json to its original content.
    
    Reviewed by overwise at 2019-04-26 18:24
  • 9. Nothing being sent to MailChimp

    Hello,

    I'm having difficulty subscribing any emails to Mailchimp. I have installed everything correctly and added in the appropriate service provider and facade in the config\app.php file, imported the laravel-newsletter.php file and this my code in the store function in my controller that I am using to test:

    Newsletter::subscribe('[email protected]');
    flash('Thank you, your email has been added.', 'success');
    return redirect()->back();
    

    When I click the submit button I am redirected back with the flash message, but nothing appears in Mailchimp. I have confirmed checking on the API Keys page that the requests are not being processed.

    I have added the MailChimp API key and associated list ID to my .env file but I am not sure that they are being read correctly because if I delete them entirely from the .env file no errors are thrown on the website, and no errors appear in laravel.log.

    The bizarre thing though is that I'm using this same package on another website and it is functioning just fine, the only difference as far as I can tell (aside from the API key & list id) is my older site uses version 3.6, while this site is using 3.7.

    Thank you.

    Reviewed by DouglasEvans at 2017-08-29 10:34
  • 10. PHP7 compatibility

    First of all, thanks for this great piece of code, are you guys planning on implementing support for PHP7 (especially the issue with static calls to non-static methods).

    Reviewed by remkobrenters at 2016-02-09 16:34
  • 11. firstName and lastName ignored

    When subscribing a user, I encounted a problem with the first and last name attributes being ignored.

    By examining the mailchimp API, it was resolved using FNAME and LNAME like so:

    Newsletter::subscribe('[email protected]', ['FNAME'=>'Rince', 'LNAME'=>'Wind']);
    
    Reviewed by SneManden at 2015-08-29 10:43
  • 12. Error: Call to undefined method Spatie\Newsletter\Newsletter::getLastResponse()

    Hi!

    I'm using this Laravel-Newsletter package. When i try a subscribeOrUpdate method, nothing happens.

    I tried getLastError() : "Unknown error, call getLastResponse() to find out what happened."

    I tried getLastResponse() : "Error: Call to undefined method Spatie\Newsletter\Newsletter::getLastResponse()"

    My clientController.php:

    namespace App\Http\Controllers;
    
    use App\Models\Client;
    use Illuminate\Http\Request;
    use Newsletter;
    
    class ClientController extends Controller
    {
       public function sendToMailchimp($idClient){
          $client = Client::find($idClient);
    
          Newsletter::subscribeOrUpdate($client->email);
          return Newsletter::getLastResponse();
       }
    }
    

    In my .env file, i have my two var, MAILCHIMP_APIKEY and MAILCHIMP_LIST_ID.

    Thanks a lot! Vincent

    Reviewed by pit07 at 2022-03-02 08:26
Create and manage advanced polls with this Telegram Bot which has many features available!
Create and manage advanced polls with this Telegram Bot which has many features available!

MasterPollBot Create and manage advanced polls with this Telegram Bot which has many features available! Requirements Local Telegram Bot API or a webh

Jun 21, 2022
A Laravel package to retrieve pageviews and other data from Google Analytics
A Laravel package to retrieve pageviews and other data from Google Analytics

Retrieve data from Google Analytics Using this package you can easily retrieve data from Google Analytics. Here are a few examples of the provided met

Jun 29, 2022
A DigitalOcean API bridge for Laravel
A DigitalOcean API bridge for Laravel

Laravel DigitalOcean Laravel DigitalOcean was created by, and is maintained by Graham Campbell, and is a DigitalOcean PHP API Client bridge for Larave

Jun 22, 2022
A GitHub API bridge for Laravel
A GitHub API bridge for Laravel

Laravel GitHub Laravel GitHub was created by, and is maintained by Graham Campbell, and is a PHP GitHub API bridge for Laravel. It utilises my Laravel

Jun 20, 2022
[DEPRECATED] A Pusher Channels bridge for Laravel

DEPRECATED Laravel now has built-in support for Pusher Channels. This is now the recommended approach to integrate Channels into a Laravel project. Cu

Jun 16, 2022
A simple API documentation package for Laravel using OpenAPI and Redoc

Laravel Redoc Easily publish your API documentation using your OpenAPI document in your Laravel Application. Installation You can install this package

Jun 10, 2022
TeleBot - Easy way to create Telegram-bots in PHP. Rich Laravel support out of the box.

TeleBot is a PHP library for telegram bots development. Rich Laravel support out of the box. Has an easy, clean, and extendable way to handle telegram Updates.

Jun 28, 2022
laravel wrapper for dicom images services

laravel wrapper for dicom images services

Jan 18, 2022
A Laravel package to help integrate Shopware PHP SDK much more easier

Shopware 6 Laravel SDK A Laravel package to help integrate Shopware PHP SDK much more easier Installation Install with Composer composer require sas/s

May 17, 2022
laravel package untuk memudahkan penggunaan MCA dengan Telegram Bot USDI di aplikasi Universitas Udayana.

MCA KubeMQ Laravel laravel package untuk memudahkan penggunaan MCA dengan Telegram Bot USDI di aplikasi Universitas Udayana. Motivasi Proyek ini berfu

Nov 17, 2021
Integrate RajaOngkir API with laravel

Baca ini dalam bahasa: Indonesia This is my package laravel-rajaongkir Installation You can install the package via composer: composer require kodepin

Jun 5, 2022
A Laravel SQS driver that removes the 256KB payload limit by saving the payloads into S3.

Simple SQS Extended Client Introduction Simple SQS Extended Client is a Laravel queue driver that was designed to work around the AWS SQS 256KB payloa

Jun 13, 2022
Google VerifiedSMS Laravel Package

Google VerifiedSMS Laravel Package This is a laravel package developed for google business communication api and verified SMS API. Before we commence

Nov 22, 2021
🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.
🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.

Telegram Bot API - PHP SDK Telegram Bot PHP SDK lets you develop Telegram Bots in PHP easily! Supports Laravel out of the box. Telegram Bot API is an

Jun 23, 2022
Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.

Laravel GraphQL This package is no longuer maintained. Please use rebing/graphql-laravel or other Laravel GraphQL packages Use Facebook GraphQL with L

Jun 20, 2022
A laravel 5 package for reading and writing to facebook graph object with ease in laravelish syntax

Fluent-Facebook Docs A laravel 5 package for reading and writing to facebook graph object with ease in laravelish syntax. Check out how easy it is to

Jun 11, 2022
A Laravel wrapper for thephpleague's Fractal package

laravel-api-response A Laravel wrapper for thephpleague's Fractal package Install Via Composer composer require lykegenes/laravel-api-response Then, a

Mar 15, 2021
This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

Mar 21, 2022
Twitch Helix API PHP Wrapper for Laravel
Twitch Helix API PHP Wrapper for Laravel

Laravel Twitch PHP Twitch Helix API Wrapper for Laravel 5+ ⚠️ Changes on May 01, 2020 Since May 01, 2020, Twitch requires all requests to contain a va

Jun 29, 2022