Automatically Posting to Facebook Page via Laravel Notifications

 A powerful feature that came out with Laravel v5.3 was Laravel Notifications. There are several numbers of notification channels created by the contributors in a github organization called laravel-notification-channels.

The notifications feature is fully available with later versions after it was launched along with the framework version v5.3. After that people started creating different notifications channel that can be used with your laravel application.

Laravel framework ships with support for sending email, SMS(via Nexmo), and Slack. If you wish to store notifications in a database, they may also be stored, so you can display.

I’ve been working on a new update for this website to make auto-posting to the facebook page via API when a new blog post is published on the website. I'm using a package that has already been created by Ahmed Ashraf.

I will give a full overview of available methods and fully functional code snippets of how I implemented it to automatically post them on my Facebook page.

Package Installation

You can easily install this package via composer:

composer require laravel-notification-channels/facebook-poster

If you are below Laravel v5.5, you need to register the service provider class to config/app.php

...
'providers' => [
   ...    
   NotificationChannels\FacebookPoster\FacebookPosterServiceProvider::class,
],
...

Next, you need to go to Facebook to generate some API credentials, to set up this Facebook Poster service.

I recently wrote a detailed blog post to cover the process for generating API credentials, visit this post "Generating Never Expiring Facebook Page Access Token".

After completing the process of generating the API credentials, put them on config/services.php

'facebook_poster' => [
    'app_id' => env('FACEBOOK_APP_ID'),
    'app_secret' => env('FACEBOOK_APP_SECRET'),
    'access_token' => env('FACEBOOK_ACCESS_TOKEN'),
],

Setup Model

In my project setup, I have a Blog model that is responsible for storing and retrieving all blog posts. I'm observing the laravel model events, laravel fires many events in different context. In my case, I am listening to the created event to automate this process.

You can use your own model related to your topic that you already have. Simply use the Notifiable trait to it.

use Illuminate\Notifications\Notifiable;

/**
 * Class Blog
 * @package App
 */
class Blog extends Model
{
    use Notifiable;

Now, create a notification class with a command:

php artisan make:notification ArticlePublished

All you need to do is, adjust via() method, and create a new toFacebookPoster() method, which will be called via FacebookPosterChannel.php class, view the complete class below.

app\Notifications\ArticlePublished.php

<?php

namespace App\Notifications;

use App\Blog;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use NotificationChannels\FacebookPoster\FacebookPosterChannel;
use NotificationChannels\FacebookPoster\FacebookPosterPost;

/**
 * Class ArticlePublished
 * @package App\Notifications
 */
class ArticlePublished extends Notification
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [FacebookPosterChannel::class];
    }

    /**
     * @param $blog
     */
    public function toFacebookPoster($blog)
    {
        return with(new FacebookPosterPost($blog->title))
            ->withLink($blog->getLink());
    }
}

Now, most interesting part is making the process automated. I'm creating an event listener to stay ready to fire up a notification when a new blog is stored in the database.

If you want to discover the supported methods, visit the github repository for the package.

You could either fire the notification via the controller after the blog post is created:

/**
 * Create a new blog instance.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    // Validate the request...

    $blog = Blog::create([
        'title' => $request->title,
        'slug' => $request->slug
        ]);

    $blog->notify(new ArticlePublished);
}

Another better way is listening to the model events, the cleaner way I like and the way I follow every single day.

Observing Model

Create a new event subscriber class under, app/Listenerscall it BlogEventSubscriber.php

<?php

namespace App\Listeners;

use App\Notifications\ArticlePublished;

/**
 * Class BlogEventSubscriber
 * @package App\Listeners
 */
class BlogEventSubscriber
{

    /**
     * Handle blog creating events.
     *
     * @param $blog
     */
    public function onCreated($blog)
    {
        $blog->notify(new ArticlePublished());
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param  Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'eloquent.created: App\Blog',
            'App\Listeners\BlogEventSubscriber@onCreated'
        );
    }
}

We need to register this class in, app/Providers/EventServiceProvider.php

    /**
     * The subscriber classes to register.
     *
     * @var array
     */
    protected $subscribe = [
        'App\Listeners\BlogEventSubscriber',
    ];

Development Issue

I tried to send the localhost link along with Facebook post but it throws an exception while sending localhost URL, so be aware of that.

    public function toFacebookPoster($blog)
    {
        return with(new FacebookPosterPost($blog->title))
            ->withLink($blog->getLink());
    }

We are done!

Conclusion

Thanks for reading this article up to the end, if you have any feedback regarding the post please feel free to leave your comment below. The code snippets are fully tested, and the full source is available in the github repository.