Scheduling Cron Job for sending newsletters in Laravel 5

Today, we will send the newsletters to our users through a scheduler. A scheduler is a laravel feature. Nowadays, many web applications need to send mail to the users either for marketing or other purposes. It’s almost impossible to send manually. Such type of task need scheduler. We will implement this in laravel 5.

Let’s get started.

Create Project & Database Setup

We will start with the fresh laravel project. Create a new project through composer running the command below:

composer create-project laravel/laravel kodementor

After installing, let’s setup our database. Create a new database and edit the details in .env file. So, my .env file for database setup looks like:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=kodementor
DB_USERNAME=root
DB_PASSWORD=secret

Create Migrations and Models

For this tutorial, we will create create a new table posts that contains blog posts. We will sent the newsletters containing these articles to the users. We will use laravel default authentication.

Let’s create authentication system by running command:

php artisan make:auth

Now, lets create model and migration for posts table. We will do it at once by running the command below:

php artisan make:model Post -m

Let’s open newly created migration file and add some columns. Our final migration looks as below:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('slug');
        $table->text('body');
        $table->text('author_id');
        $table->timestamps();
    });
}

After these setup, it’s time to migrate our tables. Run the migration:

php artisan migrate

Seeding Database

We will use tinker to seed our database with fake data. You can read a detailed article about running tinker in laravel in this link. Now, run the following command to open tinker shell.

php artisan tinker

I haven’t shown all the setup to seed database as this is out of topic. I believe you are familiar with seeding. Finally to populate our posts table and users table, run the comand:

factory(App\Post::class, 20)->create();
factory(App\User::class, 20)->create();

Create Mailable

We need to create a mailable class send a email. Run the following command:

php artisan make:mail SendNewsletter

In this SendNewsletter mailable class, we will point to the template of email for sending the newsletter.

view('emails.newsletter');
    }
}

The above build method points to the newsletter blade file under emails directory. Now, lets create a template for sending newsletter to user. Created a new file under newsletter.php under emails directory and added some code as below:




    Newsletter from Kodementor


    
@forelse($posts as $post)

{{ $post->title }}

{{ $post->body }}

@empty @endforelse

Create Artisan Command

We will create a new command for sending newsletter to the users. Let’s generate one by running the artisan command:

php artisan make:command SendNewsletter

This will create a new command in App/Console/Commands/ directory. In this command, we will give our custom command and description as below.

protected $signature = 'send:newsletter';
....
protected $description = 'Send newsletter to user';

Similaryly, handle function is used to retrieve data from database and send mail to the user. You can also check if you new command is registered or not by running the command below:

php artisan list

Thus, our final code looks like below:

take(5)->get();

         \Mail::to($users)->send(new SN($posts));
    }
}

Now, let’s try sending newsletter without scheduling our task. For this, run the command below:

php artisan send:newsletter

This will fire the command send:newsletter. I have setup my mailtrap for emails. I have got mail.

Scheduling the Artisan Command

We have successfully sent newsletter through the command. Let’s schedule the command and check if it works. For scheduling in laravel https://laravel.com/docs/5.5/scheduling, we need to write scheduler in kernel.php

// App/Console/Kernel.php
........
/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->commands('send:newsletter')
                ->everyFiveMinutes();
}
..........

Along with this, we need to add cron entry to our server.

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

For testing in localhost, we can run the command below

php artisan schedule:run

Running the above command will give us mail every minute. Off course you don’t want mail to be every five minutes. You can change the preferences according to you need.

Conslusion

This is all for task scheduling in Laravel for sending newsletter. If you have any comment or feedback, please write on the comment field.

Read More Articles

6 COMMENTS

  1. Hey just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Chrome. I’m not sure if this is a format issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the problem fixed soon. Thanks

  2. Please let me know if you’re looking for a article author for your blog.
    You have some really great posts and I believe I would be
    a good asset. If you ever want to take some of the load off,
    I’d love to write some articles for your blog in exchange for a link back to mine.
    Please shoot me an email if interested. Cheers!

  3. Hey there I am so delighted I found your website, I really found
    you by accident, while I was browsing on Askjeeve for something else,
    Nonetheless I am here now and would just like to say thank you for a marvelous post and a all round exciting blog (I also love the theme/design),
    I don’t have time to browse it all at the minute but I
    have saved it and also added your RSS feeds, so when I have
    time I will be back to read a great deal more, Please do keep up the fantastic job.
    quest bars http://bitly.com/3jZgEA2 quest bars

  4. Hello just wanted to give you a quick heads up. The text in your article seem to
    be running off the screen in Safari. I’m not sure if this is a formatting
    issue or something to do with internet browser compatibility
    but I thought I’d post to let you know. The
    design and style look great though! Hope you get the issue solved soon.
    Many thanks

LEAVE A REPLY

Please enter your comment!
Please enter your name here