Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative path for asset function for laravel

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?

like image 542
Oleg Liski Avatar asked Mar 23 '16 07:03

Oleg Liski


2 Answers

As far as I know, asset() and other helpers generate only full paths. You have two choices:

  1. Create your own helpers for relative URL generating.

  2. Create relative URLs manually.

like image 194
Alexey Mezenin Avatar answered Oct 13 '22 05:10

Alexey Mezenin


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/).

like image 24
Andrea Mauro Avatar answered Oct 13 '22 05:10

Andrea Mauro