In the digital landscape, video content has become a powerful medium for engagement. YouTube, as a prominent platform for sharing video content, offers the ability to embed videos on websites. When working with Laravel, a popular PHP framework, converting YouTube watch links to embedded links for seamless integration into web applications can greatly enhance user experience. Let’s explore how to achieve this transformation effortlessly.
YouTube provides embedded links that allow videos to be displayed directly on web pages. These links are created from the standard YouTube watch links by extracting the video ID and incorporating it into an embed URL.
if you are uploading the video statically it is not a big task you can simply write it as
https://www.youtube.com/embed/{videoID}
But if you are featching the video dynamically from the database by putting the video link throught admin panel but the video will be visible on the website until and unless the video will not be embeded so to make it easy for use to simply upload link and the video will be visible on the website we have the convert the watch link into the embeded link below are steps by following below steps you can achive this
Here I am taking the example of the posts
public function post(Request $request)
{
$post= Post::whereSlug($request->slug)->firstOrFail();
$youtubeUrl = $post->video;
// Use regular expression to extract the video code
if (preg_match('/[?&]v=([a-zA-Z0-9_-]+)/', $youtubeUrl, $matches)) {
$videoCode = $matches[1];
} else {
$videoCode = ''; // If no video code is found, set it to an empty string
}
$postVideo = $videoCode; // This will output: ks_VU8-9Hew
return view('frontend.post',compact('post','postVideo'));
}
Here we have taken the video id form the uploaded youtube link
<iframe class="img-fluid" src="https://www.youtube.com/embed/{{ $postVideo}}" frameborder="0" allowfullscreen></iframe>
This is how you can convert the watch link in the embeded link now the user can easily upload the youtube video link and the controller will automatically get the video id from the link and pass the video id in the blade and in the blade there is embed link this will make the video embed