Skip to content
Advertisement

Laravel relative paths not working as expected on localhost

I’m just using Mac OS’s native apache2 server for my localhost. In my httpd.conf file, I set

DocumentRoot "/Users/user_name/Local Sites/"

…that directory houses all my sites I work on locally:

Users
 -user_name
  --Local Sites
   ---site_1
   ---site_2
   ---site_3
   ---site_4

So, for my particular Laravel project for site_1, I set the following in .env:

APP_URL=http://localhost/site_1

…and again in config/app.php:

'url' => env('APP_URL', 'http://localhost/site_1'),

However, when I try to use one of Laravel’s relative path builders, it includes the whole path above what I had defined as my document’s root and server’s localhost. For example:

public_path() = /Users/user_name/Local Sites/site_1/public

The problem, then, is that when I use that variable to, say, link to a .js file in public/js, the generated path is

http://localhost/Users/user_name/Local%20Sites/site_1/public

…which is invalid, of course, because the proper path is really

http://localhost/site_1/public

I’m sure I’m doing something stupid, but I’m too stupid to figure out what it is! My site works when I resolve those paths explicitly, but then of course everything breaks when I publish to my web host (with absolute instead of relative paths).

Advertisement

Answer

Do not mix the use of the helper function publich_path() and assets().

You should link your JS/CSS/Img the following way:

<script src="{{asset('js/main.js')}}"/>

Laravel will translate that call into

<script src="http://localhost/site_1/js/main.js"/>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement