Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brentxscholl's avatar

Is there a way to change “Video site link” to “Video embed link” using Laravel?

I'm building a social network site with Laravel

I have a section of my site where a user can submit a URL to a video with a form ex. https://www.youtube.com/watch?v=xxxxxxxxxx

The URL gets saved in the database.

I want to embed the youtube/vimeo player on the page using an iframe.

I can grab the url using

$video->url

In order to display the iframe I use

<iframe width="306" height="200" src={{ $video->url }} frameborder="0" allowfullscreen></iframe>

The space is there but no video. Just blank space. I figure this is because the link is not the embed link youtube provides which should be //www.youtube.com/embed/xxxxxxxxxx

Is there a Laravel way to convert site URLs to embed URLs? I don't want to make my users submit the embed URL since most people don't know about it and it's easier for them to just submit the URL in their browser

0 likes
4 replies
RachidLaasri's avatar
Level 41

What you should do is save the key to your database.

This function will parse the URL and return the video ID.

    function YoutubeID($url)
    {
        if(strlen($url) > 11)
        {
            if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match))
            {
                return $match[1];
            }
            else
                return false;
        }

        return $url;
    }

Save it to your database, and embed the video using

<iframe width="560" height="315" src="http://www.youtube.com/embed/{{$video->key}}" frameborder="0" allowfullscreen></iframe>
5 likes
pmall's avatar

Yes then use a mutator to automagically set the video key attribute when saving to the database :

class Video extends Model{

  public function setKeyAttribute($value)
  {
    $this->attributes['key'] = $this->youtubeId($value);
  }

}
1 like
bensampo's avatar

This is an old question, but I'm hoping this reply will help any future Google searchers as this question ranks pretty highly.

The laravel-embed package can help by giving you the ability to embed a YouTube video (and others) using a blade component:

<x-embed url="https://www.youtube.com/watch?v=oHg5SJYRHA0" />

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.

Please or to participate in this conversation.