Laravel external URL issue

2019-07-31 18:04发布

问题:

I want to set external URL in some of my anchor tags but facing problem when URL is without http/https protocol. When URL is without these protocols URL become like following:

<a target="_blank" href="www.usatoday.com/"></a>

when I click on it or hover over it, it shows and redirect me to: http://localhost/event/www.usatoday.com

I've tried following two ways in href but didn't worked:

{{url($eventSponsorsRow->sponsorUrl)}}
{{ $eventSponsorsRow->sponsorUrl }}

instead of URL in href. Laravel 5.3

回答1:

This is HTML and browser stuff, not Laravel/PHP itself.

You just need to provide protocol part of the url to make it external.

You can skip the http: but it needs at least double slash in front of the url like:

<a target="_blank" href="//www.usatoday.com/"></a>

Please not, that if you skip the http(s): part it will use currently used protocol.



回答2:

You need to prepend http:// to the url

if you want to use {{url($eventSponsorsRow->sponsorUrl)}} make sure when you insert into a database it prepends http:// with it

<a target="_blank" href="{{ url($eventSponsorsRow->sponsorUrl) }}"></a>

if you don't want to do that you will need to create a variable with the url you are getting from the database and prepend the http://

$newvariable = "http://$eventSponsorsRow->sponsorUrl"; and call the $newvariable in the correct location

<a target="_blank" href="{{ $newvariable }}"></a>

https://laracasts.com/discuss/channels/laravel/laravel-blade-external-url-link-reading-url-from-database