Hello artisan,
In this Laravel URL validation example tutorial, I am going to show you how to validate URL in Laravel. I will show you many ways to validate URLs in Laravel. I will show you URL validation with regex, regular expression, Laravel default URL validation helper and finally using FILTER_VALIDATE_URL to validate email.
We can validate URLs in Laravel in many ways. I will show you some of them. Hope this URL validation example tutorial will help you to learn how to validate URL in PHP Laravel application. Let's start:
The first way, we can validate URL using regex. This method also validate URL even if the URL does not contain http://
or https://
. Let's see an example:
public function store(Request $request)
{
$regex = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
$input = $request->validate([
'url' => 'required|regex:'.$regex,
]);
}
Laravel has many default validation rules. In Laravel, url
validation rule checks that field should be URL. Let's see its example:
public function store(Request $request)
{
$input = $request->validate([
'url' => 'required|url'
]);
}
We can also validate email using FILTER_VALIDATE_URL
like:
$url = 'https://codecheef.org';
if(filter_var($url, FILTER_VALIDATE_URL)) {
//valid
} else {
//invalid
}
Read also: Laravel Email Validation Using Regex Example
You can test now. Hope it can help you.
#laravel