How to add an external URL in Laravel balde

If you have a url that you want to get from DB and put it into Laravel blade and you want it to be linkable you may face a problem if the link doesn’t contain http:// as the browser will treat it as a page inside the current website.

For ex. if the link is external.com the html will be :

in Blade :

<a href = "{{ $site_url }}"> {{ $site_url }} </a>

in html:

<a href = "external.com">exterlnal.com</a>

The problem here is that when you click on that link , the browser will go to : www.mysite.com/exterlan.com

which will give you a 404.

You may think that to need to add http:// or https:// but all you need to add is just the // but then what if the url is saved with http:// or https:// then you better check for it first

<a href="@if(!str_contains( "$site_url", '//'))//@endif{{$site_url}}" target='_blank'>
                      {{ $site_url }}
                    </a>

ps. str_contains is a PHP8 function

Leave a Reply

Your email address will not be published.