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
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>
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);
}
}
Very clever RachidLaasri! Thank you!
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 sign in or create an account to participate in this conversation.