I am using laravel 5.1 framework and I want to use asset() function in blade templates.
Problem is that my application can have different domains: http://www.domain1.com and http://www.domain2.com in development mode.
When I use correct asset() syntax, it adds full path to a file, including domain.
<link href="{{ asset("/css/style.css") }}" type="text/css" />
converts to
<link href="http://www.domain1.com/css/style.css" type="text/css" />
Question is: Is it possible to configure laravel, so it will not add full domain name. Expected result is:
<link href="/css/style.css" type="text/css" />
Any ideas?
As far as I know, asset()
and other helpers generate only full paths. You have two choices:
Create your own helpers for relative URL generating.
Create relative URLs manually.
I found a workaround that I hope doesn't have any contraindications.
You could set ASSET_URL=" "
in your .env
file.
ASSET_URL
contains the prefix that will be used for your asset()
helper, when it's value is empty (it is by default) it will use your APP_URL
instead.
Using " "
as a prefix will make sure that all your asset paths will start from the root of any domain you are using (ex. <link href=" /css/app.css" rel="stylesheet">
, note the space before the URL).
Using this solution you can easily switch to a CDN in the future just changing your ASSET_URL
setting.
The bad thing is that it adds a space prefix to all asset urls, browsers ignore that but you may encounter other issues when working with javascript.
A case I could think of where this would not work is when you can access the site from different directory levels (ex. http://www.domain1.com/ and http://www.domain2.com/subpath/).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With