skip to Main Content

To start, I know that this has been answered for previous versions of Laravel (example SO Post), but in 11, it seems like things have changed.

In my project, Ihave a structure like:

/
    ...
    resources/
        css/
            main.css
        js/
            main.js
        media/
            logo.jpg
        views/
            ...

I would like to include other resources in my views, but it seems like solutions from previous versions are no longer valid:

{{HTML::script('js/main.js')}} Says that HTML can’t be found with an error screen

{{ url('/css/main.css') }}, {{ asset('/css/main.css') }} both return http://localhost:8000/css/main.css, but that hits a 404 when accessed.

What is the modern way to access other resources? I know I could probably put things in the public directory, but this route felt more correct?

2

Answers


  1. Don’t refer to old information. Read the official documentation.

    Front-end skills are required when using Laravel.

    If you don’t know anything about the front-end, just put all files in public.

    public/
      - css/
      - js/
      - media/
    

    Then use it in blade

    <script src="{{ asset('js/main.js') }}" defer></script>
    <link href="{{ asset('css/main.css') }}" rel="stylesheet">
    
    Login or Signup to reply.
  2. This is more about the server configuration that the framework itself. For security reasons only what’s inside the public directory can be freely accessible from the outside (if not configured otherwise), so if you locate your assets somewhere else, the requests for trying to reach them will fail.

    That’s why you have to place the files yourself somewhere inside /public or to use a tool like vite or mix to automate the process which in this basic scenario would be just to copy your files. Even though not recommended, you could create a symlink on /public pointing a subdirectory inside your /resources but you must be careful not to expose more than required, like your views.

    How does asset() work?
    This helper calls to app('url')->asset($path, $secure). app('url') resolves to a UrlGenerator singleton that was created with the app.asset_url configuration (which can be modified via the ASSET_URL env variable) so when calling ->asset() the generated URL will contain the asset_url as root or the request root as fallback.

    You don’t want to use the url helper which does something similar but is meant to be used with other kind of files like a pdf uploaded by some user which may be stored in another filesystem like S3.

    I’d also suggest you to search info about Laravel asset building.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search