I talk about code and stuff
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:
So, I split this out into a separate package with a class you can use without the aforementioned limits.
$url = new ShareableLink('http://example.com/', 'Example Site');
echo $url->facebook;
// https://www.facebook.com/dialog/share?app_id=ABC123&href=https://example.com/&display=page&title=Example+Site
echo $url->twitter;
// https://twitter.com/intent/tweet?url=https://example.com/&text=Example+Site
echo $url->whatsapp;
// https://wa.me/?text=Example+Site+https%3A%2F%2Fexample.com%2F
echo $url->linkedin;
// https://www.linkedin.com/shareArticle?mini=true&url=https://example.com/&summary=Example+Site
echo $url->pinterest;
// https://pinterest.com/pin/create/button/?media=&url=https://example.com/&description=Example+Site
echo $url->google;
// https://plus.google.com/share?url=https://example.com/**
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('news.show', $this->slug);
return new ShareableLink($url, $this->title);
}
}
Check it out and get the package from GitHub below.