Laravel stylesheets and javascript don't load for non-base routes
Okay--I know this is a really elementary issue, but I can't figure it out. This is a question regarding Laravel.
Basically, I have my stylesheets embedded in my default layout view. I'm currently just using regular css to link them, such as:
<link rel="stylesheet" href="css/app.css" />
It works great when I am at a single level route such as /about, but stops working when I go deeper, such as /about/me.
If I look at Chrome's developer console I see some of the following errors (only for the deeper routes):
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://example.dev/about/css/app.css".
So clearly it is now looking for the css inside the "about" folder--which of course isn't a folder at all.
I just want it to look in the same place for the assets regardless of the route.
Solution 1:
For Laravel 4 & 5:
<link rel="stylesheet" href="{{ URL::asset('assets/css/bootstrap.min.css') }}">
URL::asset
will link to your project/public/
folder, so chuck your scripts in there.
Note: For this, you need to use the "Blade templating engine". Blade files use the
.blade.php
extension.Solution 2:
Laravel 4
The better and correct way to do this
Adding CSS
HTML::style will link to your project/public/ folder
{{ HTML::style('css/bootstrap.css') }}
Adding JS
HTML::script will link to your project/public/ folder
{{ HTML::script('js/script.js') }}
Solution 3:
You are using relative paths for your assets, change to an absolute path and everything will work (add a slash before "css".
<link rel="stylesheet" href="/css/app.css" />
Solution 4:
in Laravel 5,
there are 2 ways to load a js file in your view
first is using html helper, second is using asset helpers.
to use html helper you have to first install this package via commandline:
composer require illuminate/html
then you need to reqister it, so go to config/app.php, and add this line to the providers array
'Illuminate\Html\HtmlServiceProvider'
then you have to define aliases for your html package so go to aliases array in config/app.php and add this
'Html' => 'Illuminate\Html\HtmlFacade'
now your html helper is installed so in your blade view files you can write this:
{!! Html::script('js/test.js') !!}
this will look for your test.js file in your project_root/public/js/test.js.
//////////////////////////////////////////////////////////////
to use asset helpers instead of html helper, you have to write sth like this in your view files:
<script src="{{ URL::asset('test.js') }}"></script>
this will look for test.js file in project_root/resources/assets/test.js