Awell's avatar

Linking assets outside of /public - Modular App

I'm building a basic modular CMS, each module can contain 'blocks' which are blade templates that can be used in the page builder. I want all the files for a module contained in a single folder, so I want the assets for a block to be loaded from the blocks directory inside the module directory. This is the current directory structure of the modules.

app/
  |-- Modules/
      |-- Blog/
          |-- Config/
          |-- Console/
          |-- Database/
              |-- Migrations/
              |-- Seeds/
          |-- Http/
              |-- Controllers/
              |-- Middleware/
              |-- Requests/
              |-- routes.php
          |-- Providers/
              |-- BlogServiceProvider.php
              |-- RouteServiceProvider.php
          |-- Resources/
              |-- Blocks/
                  |-- headers/
                      |-- header-large.blade.php
                  |-- css/
                      |-- skeleton.blade.php
                      |-- style.css
              |-- Lang/
              |-- Views/
          |-- module.json

From skeleton.blade.php I want to be able to link the style.css, but I can't since it's not within the public directory. How do I link assets outside of /public?

0 likes
3 replies
henrique's avatar
Level 3

You will need to create a route for it, something like this:

Route::get('/assets/{module}/{type}/{file}', [ function ($module, $type, $file) {
    $module = ucfirst($module);

    $path = app_path("Modules/$module/Resources/Blocks/$type/$file");

    if (\File::exists($path)) {
        return response()->download($path, "$file");
    }

    return response()->json([ ], 404);
}]);

Then you link to base_url('/assets/blog/css/style.css');

1 like
bashet's avatar

@henrique

I followed your instruction. It works fantastic for js file. But it does not work for css file.

For css file, it creates the link which is fine, but style does not apply the style to the elements. When I try to access the css file via browser from page source, it force for download!

However, as I am using 5.2, I tried as below

return response()->file($path);

Now it doesn't force for download and I can see my css stylesheet via browser, but still it doesn't apply the style to elements! Any idea what I can do ?

bashet's avatar

Hello everybody, I solved the problem. in my case, I had to use second perameter to output the file as below:

if($type == 'js'){
            return response()->file($path, array('Content-Type' => 'application/javascript'));
        }else{
            return response()->file($path, array('Content-Type' => 'text/css'));
        } 
1 like

Please or to participate in this conversation.