Embedding media by its public URL using laravel-embed
A client came to me with a new requirement for their website: to be able to embed content from multiple services (YouTube, Vimeo, Slideshare etc.). This is a fairly common requirement, particularly for embedding things like YouTube videos and it's a problem I've solved multiple times.
Each time I've done it, my approach has usually been to ask the client to fill in a "Video ID" field in the CMS. I can then use this ID to generate the appropriate embed code for the view.
This is pretty straightforward from a technical standpoint, but it's not ideal for a few reasons:
- It's reliant on the client's technical ability to extract things like a YouTube video id from a URL. Or worse, an ID from the embed code if the URL isn't all that's needed.
- It's a waste of time for the client
- It's error prone
Wouldn't it be better if they could just put in the URL of the thing they want to embed?
Of course, but then it's up to the application to perform the task of generating the embed code from the URL... That's why I made laravel-embed.
Using laravel-embed
At its heart, laravel-embed exposes a single blade component (added in Laravel 7). You pass in a url
attribute for the thing you want to embed and it will do the job of fetching the necessary parameters for the iframe, either by getting it from the URL or using oEmbed for some services where that's not possible. It'll then render the iframe itself. It's as simple as:
<x-embed url="https://www.youtube.com/watch?v=oHg5SJYRHA0" />
It's responsive
Most generated embed code isn't responsive. Surprisingly even from the big services like YouTube, they still define a set width/height. This isn't much good for a modern, responsive website.
There's a neat CSS padding trick to getting iframes to display responsively while maintaining their aspect ratio which this package makes use of.
Generally I want to embed things at a ratio of 16:9 (which is standard for modern videos), but if that's not the case, and I want to embed an old video at a 4:3 ratio, I can do that too by passing a value to the aspect-ratio
attribute.
<x-embed url="https://www.youtube.com/watch?v=oHg5SJYRHA0" aspect-ratio="4:3" />
Supported services
For now, the package supports a few of the major embed services that I've dealt with in the past such as YouTube, Vimeo and Slideshare. You can see the full list of supported services.
I've built it in such a way as to be extended with more services if required.
Fallback
You might be wondering what happens if you give the blade component a URL which it doesn't know how to handle...
<x-embed url="https://www.this-does-not-exist.com" />
In that case it'll render a fallback view. This view (and each of the views for the individual services) can be published to your application to be modified as desired.
Wrapping up
If you want to make use of this package, head over to the GitHub repository and follow the installation instructions.