Embed and Parse Youtube/Vimeo Videos with Laravel Embed Package

I’ve recently found a simple package that helps to transform any URL into embeddable HTML, the best examples are Youtube and Vimeo videos.

Let’s imagine you have a video input text field (not uploadable video but URL), which you than need to transform into HTML code, depending on the platform.

So, some users may specify Youtube video:

Others may add a link from Vimeo platform:

And in the final result, you probably want both to be working, like in this table:

We have a Laravel package to help: KaneCohen/embed

The usage is pretty simple.

Step 1. Installation.

Add to composer.json “require” section:

"cohensive/embed": "5.5.*"

Step 2. config/app.php: add provider and alias

// ... Providers array ...
Cohensive\Embed\EmbedServiceProvider::class,

// ... Aliases array ...
'Embed' => Cohensive\Embed\Facades\Embed::class,

Step 3. Eloquent Accessor Field

Let’s attach the embedded HTML to an accessor field of app/Product.php model:

use Cohensive\Embed\Facades\Embed;

class Product extends Model
{

    public function getVideoHtmlAttribute()
    {
        $embed = Embed::make($this->video)->parseUrl();

        if (!$embed)
            return '';

        $embed->setAttribute(['width' => 400]);
        return $embed->getHtml();
    }

}

Step 4. View Embedded HTML

In the Blade code, you just need to view this:

{!! $product->video_html !!}

I haven’t tested, but the package has more support for embeddable platforms, see its configuration file:

  • youtubePlaylistVideo
  • youtubePlaylist
  • youtube
  • liveleak
  • vimeo
  • dailymotion
  • gametrailers
  • ign
  • vine
  • coub
  • kickstarter
  • ustream
  • twitchArchive
  • twitchArchiveChapter
  • twitch
  • html5video
  • gfycat
  • web.tv

Like our articles?
Check out our Laravel online courses!

6 COMMENTS

  1. The laravel-embed package (https://github.com/BenSampo/laravel-embed) can help by giving you the ability to embed a YouTube videos (and others) using a blade component:

    You simply pass the public URL of the video into the url attribute and the package will handle the rest.

    Additionally there are validation rules for all the services supported by the package (it’s not just YouTube) and it’s responsive out of the box.

LEAVE A REPLY

Please enter your comment!
Please enter your name here