Mohamed Benhida

admin@devma.net

December 20, 2017

Facebook Api in Laravel

We saw how to use twitter api in laravel now we will talk about how can we handle facebook api.

We will take the same example we want to share each new Post added on facebook.

First we need to install this package php-graph-sdk using this command

composer require facebook/graph-sdk

we come to Facebook Developers then we create an application

config/services.php

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

Then we create a job php artisan make:job SendFacebook 

<?php

namespace App\Jobs;

use App\Post;
use App\Tag;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SendPageFacebook implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $post;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (! app()->environment('production')) {
            Log::info("Facebook Posting");
            return;
        }

        $fb = new \Facebook\Facebook([
          'app_id' => config('services.facebook.app_id'),
          'app_secret' => config('services.facebook.app_secret'),
          'default_graph_version' => 'v2.10',
          'default_access_token' => config('services.facebook.access_token'),
        ]);

        $linkData = [
         'link' => $this->post->url,
         'message' => $this->toMessage($this->post)
        ];


        try {
         $response = $fb->post('/me/feed',$linkData);
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            return false;
         exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            return false;
         exit;
        }
        return true;
    }

    protected function toMessage(Post $post): string
    {
        $tags = $post->getTags()
            ->map(function (Tag $tag) {
                return "#{$tag->name}";
            })
            ->implode(' ');

        return $post->title
            . PHP_EOL . $tags;
    }
}

Now we add this to our save method on Post Model

Post.php

<?php

namespace App;

use App\Jobs\SendFacebook;

class Post extends Model
{
    protected $fillable = [
        'title', 'image', 'description','slug','status','featured','content','category'
    ];

    public function save(array $options = [])
    {
        parent::save();
        SendFacebook::dispatch($this);
        
    }
}

Each Post added it will be shared on your facebook application feed.

Astuce :

If you want your Post looked good on Facebook you need to add this meta in your <head> 

<meta property="og:description" content="Small description">
<meta property="og:url" content="{{ request()->fullUrl() }}">
<meta property="og:image" content="{{ asset('Picture') }}">
<meta property="og:title" content="{{ $post->title }}">

© Mohamed Benhida.

Blog | Packages | About