Relative path for asset function for laravel
Asked Answered
P

5

7

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?

Phalanstery answered 23/3, 2016 at 7:57 Comment(3)
I thought the asset method generates a url based on the current domain?Florilegium
Why don't you write directly /css/style.css in the link?Maternal
I haven't tested but... wouldn't that mean that when you have a url like domain1.com/users/123/, it won't locate the resource because it will look for the css in path users/123/css/style.css ?Price
N
4

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

Noam answered 6/2, 2020 at 18:45 Comment(0)
A
4

This works for me;

parse_url(asset('path/to/asset'), PHP_URL_PATH)
Alphosis answered 18/6, 2020 at 17:7 Comment(0)
L
3

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.

Legislator answered 23/3, 2016 at 8:8 Comment(0)
T
3

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">.

Torgerson answered 12/6, 2021 at 7:30 Comment(0)
D
1

Add this line in your head:

<base href="/yourapp" /> 

it's quick solution!

Dilorenzo answered 13/2, 2019 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.