Laravel 10 Add Facebook Like & Share Post Button Tutorial

Last Updated on by in Laravel

In today’s interconnected world, social media presence is critical for any website’s success. Adding Facebook Like and Share buttons to your Laravel application can significantly boost the visibility and engagement of your blog posts.

By integrating these buttons, readers can easily share your content with their networks, potentially reaching a much wider audience. This comprehensive guide will walk you through the process of incorporating Facebook Like and Share buttons into your Laravel application, specifically for your blog posts.

First, let’s ensure you have a Laravel project set up and ready to go. We’ll use the Blog model and its corresponding factory, as shown in the subsequent section, to simulate a blog setup with dynamic data generation. This guide assumes you are already comfortable working with Laravel and are familiar with basic concepts such as routes, views, and controllers.

In the steps to come, we’ll cover how to add Facebook’s SDK to your application, integrate the Like and Share buttons into your blog post views, and customize them according to your needs.

Let’s get started with this exciting journey to enhance your blog’s social media presence!

How to Add Facebook Like and Share Post Button in Laravel 10

  • Step 1: Install Laravel Project
  • Step 2: Add Database Details
  • Step 3: Model and Migrations
  • Step 4: Add Fake Records with Tinker
  • Step 5: Create Controller
  • Step 6: Add Routes
  • Step 7: Integrate Facebook Like and Share Button in Posts
  • Step 8: Start Laravel App

Install Laravel Project

Open console, type command and hit enter to start installing the new laravel app.

composer create-project --prefer-dist laravel/laravel laravel-demo

Add Database Details

Connecting to database is required when interacting with database, hence update given code in .env configuration file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Model and Migrations

Often, like and share buttons are added to blog posts, create a model and migration file using the given PHP artisan command.

php artisan make:model Blog -m

In the table, create title and content values, add props in the database/migrations/create_blogs_table.php file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Similarly, head over to model file, define the table props in app/Models/Blog.php file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
    use HasFactory;
    protected $fillable = [
        'title',
        'content',
    ];    
}

Now, run the migration command to generate a new table in the database.

php artisan migrate

Add Fake Records with Tinker

Next, we will generate a factory file that allows us to generate fake records in the laravel app and execute the provided command.

php artisan make:factory BlogFactory --model=Blog

Get into the database\factories\BlogFactory.php, define the faker properties associated with fake records:

<?php
namespace Database\Factories;
use App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class BlogFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Blog::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'url' => Str::slug($this->faker->name),
            'category' => $this->faker->name,
            'description' => $this->faker->text,
        ];
    }
}

All set, now use the tinker command to create dummy records.

php artisan tinker
Blog::factory()->count(55)->create()

Create Controller

In this step, you will create a new controller; in this file, we will add the logic to fetch records from the database and pass it to the view template.

php artisan make:controller BlogController

Above command generated new blog controller, thereafter get into the app\Http\Controllers\BlogController.php and update with the given code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;

class BlogController extends Controller
{
    public function index()
    {
        $blogs = Blog::all();
        return view('index', compact('blogs'));
    }
}

Create Route

In this step, define the route which will interact with the controller and fetch the result from the database. Head over to routes/web.php add place the recommended code.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
Route::get('/', [BlogController::class, 'index']);

Integrate Facebook Like and Share Button in Posts

Create index.php, get post data and display into the bootstrap cards, most importantly define the Facebook JavaScript SDK to add the share and like buttons in laravel, insert the given code in resources/views/index.blade.php file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Add Facebook Like and Share Buttons in Laravel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
       .container {
           max-width: 600px;
       }
    </style>
</head>
<body>
    <div class="container mt-4">
        @foreach($blogs as $blog)
            <div class="card mb-3">
                <div class="card-body">
                    <h5 class="card-title">{{$blog->title}}</h5>
                    <p class="card-text">{{$blog->content}}</p>
                    
                    <div class="likeShareBtnmt-3">
                        <div id="fb-root"></div>
                        <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v11.0" nonce="ccaa4s"></script>
                        <div 
                            class="fb-like" 
                            data-layout="standard" 
                            data-action="like" 
                            data-size="large" 
                            data-show-faces="true" 
                            data-href="https://developers.facebook.com/docs/plugins/" 
                            data-share="true">
                        </div>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
</body>
</html>

You may get the JavaScript SDK from Facebook developer dashboard, go there and grab the like and share button code for your laravel site.

  • Set the URL of your webpage where you are placing the Like button
  • Customized your Like button
  • See a preview of your button
  • Click the Get Code, and copy and paste the code into your webpage

Facebook JavaScript Like Share SDK

Start Laravel App

The like and share buttons have been added to laravel, run the laravel development server.

php artisan serve

Lastly, use the provided url to test the app.

http://127.0.0.1:8000

Implement Facebook Like and Share Buttons in Laravel

Conclusion

By following this guide, you can easily implement Facebook Like and Share buttons to your Laravel application, encouraging user engagement and increasing your Laravel blog application reach.

Share your newfound knowledge with others and boost your website’s visibility today!

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.