Manage newsletters in Laravel

Overview

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.

Issues
  • added function for loading all interest categories in a list

    added function for loading all interest categories in a list

    I need to be able to retrieve all interest categories for a project, and I thought this functionality could helper other people

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

    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.

    opened by flyingcoder 13
  • Resubscribing not working

    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?

    opened by andonovn 12
  • Case sensitivity fix

    Case sensitivity fix

    opened by remkobrenters 10
  • Non-static method Spatie\Newsletter\MailChimp\Newsletter::subscribe() should not be called statically

    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

    opened by danmurf 10
  • Invalid MailChimp API key supplied

    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.

    opened by maximusblade 10
  • Subscribe method response return false everytime

    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

    opened by ramzan07 10
  •  Trying to get property of non-object

    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 ```
    opened by taytus 9
  • Newsletter::subscribe Unknown error, call getLastResponse() to find out what happened. error

    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!

    opened by luan0508 9
  • Subscribe or update

    Subscribe or update

    • [x] Subscribe or update
    opened by jrean 9
  • Migrate to PHP-CS-Fixer 3.x

    Migrate to PHP-CS-Fixer 3.x

    opened by shuvroroy 0
  • Can not find list

    Can not find list

    I have set up the config file and run php artisan config:clear. But when I run Newsletter::subscribe i get a list not found exception.

    I ran dd(Newsletter::getApi()->get('lists')); and can see the list in the out put. Am I missing somtnig?

    opened by MikePageDev 0
Releases(4.10.0)
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

Graham Campbell 472 Jun 6, 2021
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

Graham Campbell 392 May 8, 2021
[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

Pusher 410 May 7, 2021
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

Spatie 2.5k Jun 13, 2021
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

Steve McDougall 3 May 19, 2021
PHP package to manage google-api interactions

Google-api-client PHP package to manage google-api interactions Supports: Google Drive API Google Spreadsheet API Installation composer require obrio-

OBRIO 3 May 13, 2021
oursms.app client library that allows you to send SMS

Oursms laravel client https://oursms.app client library that allows you to send SMS Installation Install oursms client with composer composer requir

Khalid Mohammad 11 Jun 11, 2021
A simple PHP GitHub API client, Object Oriented, tested and documented.

PHP GitHub API A simple Object Oriented wrapper for GitHub API, written with PHP. Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is

KNP Labs 1.9k Jun 18, 2021
Official repository of the AWS SDK for PHP (@awsforphp)

AWS SDK for PHP - Version 3 The AWS SDK for PHP makes it easy for developers to access Amazon Web Services in their PHP code, and build robust applica

Amazon Web Services 5.2k Jun 18, 2021
PHP 5.3+ library which helps you to interact with the DigitalOcean API

DigitalOcean The version 2 of the API will be available soon ! Please visit DigitalOceanV2 and contribute :) This PHP 5.3+ library helps you to intera

Antoine Kirk 158 May 4, 2021