How to validate URL in Laravel
While developing a web application, it's very crucial to validate URL's correctly. There are many approaches we can follow to validate any URL. One of the best approach among is of using isUrl() in Laravel. It keeps our code clean and easy to understand.
In this article we will see how to use Str::isUrl() in Laravel to effectively validate url's. The Str::isUrl() function was added in Laravel 9.
It makes it easy to verify if a string is a validly formatted URL.
👉 Example:
public function isValidUrl(){ $url = "https://cotysh.in"; if (Str::isUrl($url)) { dd("✅ Valid URL"); } else { dd("❌ Not a valid URL"); } }
Output:
✅ Valid URL
This spares you from typing out lengthy regular expressions or repeatedly calling filter_var($string, FILTER_VALIDATE_URL) which a PHP solution to validate URL's.
🛠️ How Does It Work?
Internally, Str::isUrl() employs PHP's filter_var with FILTER_VALIDATE_URL flag. So, it adheres to a tried and tested method of validating URLs, without the requirement of custom regex logic.
Example :
Str::isUrl("http://cotysh.in"); // true Str::isUrl("https://thedevnerd.com"); // true Str::isUrl("ftp://example.com"); // true Str::isUrl("thedevnerd.com"); // false Str::isUrl("hello world"); // false
🎉 Final Thoughts:
The Str::isUrl() method in Laravel is a tiny but powerful helper that improves readability, saves time, and avoids repetitive code. Anytime you’re handling strings that should represent URLs – whether from user input, APIs, or redirects – this method is your go-to tool.