roy
roy

Reputation: 361

Right way to insert JS or CSS assets in Laravel views

I am a beginner to laravel and have encountered a highly complicated issue. I am creating a route with parameters which passes the data to the controller. Fairly simple so far. But then once my function in the controller, showProject($id), returns the View that I have provided, the CSS/Javascript that are located in the public folder are not being loaded. Thats ONLY the case when I provide parameters to the route, my css and javascript seem to get routed to a different location thus failing to load in my application.

I get the error "Failed to load resource: the server responded with a status of 404 (Not Found)" but my css and javascript are all in public/css or public/js folder. for some reason, it is looking for public/viewproject/css or public/viewproject/js instead of public/js and public/css. Why is this happening?

Route.php

Route::get('viewProject/{id?}', 'ProjectController@showProject');

ProjectController.php

public function showProject($id){
  Some code ...

 return View::make('viewproject');
}

Upvotes: 1

Views: 1881

Answers (3)

peter.babic
peter.babic

Reputation: 3374

Make sure you define your CSS and JS files correctly. The right way using HTML is

<link rel="stylesheet" href="{{ asset('css/style.css') }}">
<script type="text/javascript" src="{{ asset('js/script.js') }}"></script>

or using methods

{{ HTML::style('css/style.css', ['rel' => 'stylesheet']); }}
{{ HTML::script('js/script.js', ['type' => 'text/javascript']); }}

Note that type="text/javascript" is mostly omited and used for in-line scripts.

Upvotes: 3

ahjashish
ahjashish

Reputation: 573

This is happening because you are using the css and js paths relative to the page. Use absolute paths instead.

Upvotes: 0

Dave Morrissey
Dave Morrissey

Reputation: 4411

You probably use a relative path (e.g. css/my.css), so when you're in a subdirectory the path is invalid. Use an absolute path for your CSS and JS instead (e.g. /css/my.css).

This isn't specific to laravel, it's true of any website.

Upvotes: 4

Related Questions