PHP Shareable Social Media Links

by Liam Hammett · 2 minute read · #open-source #php

This is an old post!

This post was written over 2 years ago, so its content may not be completely up-to-date. Please take this into consideration when reading it.

I recently had the need to generate various “shareable” links to help share a particular URL to different social media platforms. The problem is that every platform requires information in a slightly different way.

Lo and behold, just a few days later, Dennis Smink shared their method of doing so in their article “Laravel Shareable Trait” that covers the few biggest platforms.

While their solution certainly works, I had a couple of issues with the implementation of it:

  • Due to some functions used, its usage is limited to Laravel projects only, and to a trait on an Eloquent model
  • There’s a lot of needless repetition in the source
  • I don’t like the API it has — the options are limited to Eloquent columns and it’s not immediately clear how the trait is to be configured.

So, I split this out into a separate package with a class you can use without the aforementioned limits.

$url = new ShareableLink('', 'Example Site');

echo $url->facebook;

echo $url->twitter;

echo $url->whatsapp;

echo $url->linkedin;

echo $url->pinterest;

echo $url->google;

Instead of a trait on an Eloquent model with an awkward configuration, you can just add a custom method so you have full control of the URL and title, if you wish to create them dynamically.

class News extends Model
    public function getShareUrlAttribute()
        $url = route('', $this->slug);

        return new ShareableLink($url, $this->title);

Check it out and get the package from GitHub below.

Photo of Liam Hammett

Liam Hammett

Full-stack software developer that loves working with PHP, Laravel and Vue.