You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.4动态路由中如何保留样式与JS文件加载

Fix for Asset Loading Issues on Dynamic Routes in Laravel

Hey there! The most common reason your CSS/JS files aren’t loading on the /main/1/edit route is that you’re using relative file paths instead of absolute ones in your main.blade.php (or the layout it extends).

Here’s what’s happening: When you’re on the root-level route /main, a relative path like css/style.css resolves to http://127.0.0.1:8000/css/style.css—which is correct. But when you’re on /main/1/edit, that same relative path tries to load from http://127.0.0.1:8000/main/1/css/style.css, which doesn’t exist.

Let’s fix this with these straightforward solutions:

Replace all your relative asset paths with the asset() function, which generates an absolute URL to your public directory. For example:

<!-- Instead of this (relative path): -->
<link rel="stylesheet" href="css/style.css">
<script src="js/app.js"></script>

<!-- Use this (absolute path): -->
<link rel="stylesheet" href="{{ asset('css/style.css') }}">
<script src="{{ asset('js/app.js') }}"></script>

2. Use the url() Helper

Similar to asset(), the url() helper creates an absolute URL. It works well if you need to reference files outside the public directory (though for assets, asset() is more standard):

<link rel="stylesheet" href="{{ url('css/style.css') }}">

3. For Vite-Based Laravel Projects (Laravel 9+)

If you’re using Vite (the default in newer Laravel versions), use the @vite directive in your blade file. This automatically handles correct asset paths, even for dynamic routes:

@vite(['resources/css/app.css', 'resources/js/app.js'])

Make sure your vite.config.js is set up correctly (it should be by default) to compile assets into the public directory.

4. Add a <base> Tag to Your Layout

You can add a <base> tag in the <head> section of your master layout. This tells the browser to resolve all relative URLs from the root of your application:

<head>
    <base href="{{ url('/') }}">
    <!-- Rest of your head content -->
</head>

Note: This works great if your app is hosted at the root domain. If you ever move it to a subdirectory, you’ll need to update the href value here.

Quick Check

After making these changes, clear your browser cache (or do a hard refresh with Ctrl+F5) to ensure the browser loads the updated paths. Also, double-check that your CSS/JS files are actually in the public/css and public/js directories (or wherever you’re referencing them from).

That should resolve the asset loading issue on your dynamic route!

内容的提问来源于stack exchange,提问作者Nilaksha Perera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:36:23