Oleg Liski
Oleg Liski

Reputation: 583

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?

Upvotes: 8

Views: 8743

Answers (5)

GregThB
GregThB

Reputation: 293

I fixed the space character by setting ASSET_URL='/.' in the .env file. That makes asset url like <link rel="stylesheet" href="/./css/app.css">.

Upvotes: 3

Daantje
Daantje

Reputation: 2486

This works for me;

parse_url(asset('path/to/asset'), PHP_URL_PATH)

Upvotes: 4

Andrea Mauro
Andrea Mauro

Reputation: 842

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

Upvotes: 5

y.iragui
y.iragui

Reputation: 56

Add this line in your head:

<base href="/yourapp" /> 

it's quick solution!

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

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.

Upvotes: 3

Related Questions