skip to Main Content

I need help with my Laravel Blade view. Currently i’m using <link href="{{asset('css/sample.css')}}" rel="stylesheet"> to generate the path to my sample.css in my public folder every time. Which it’ll generate something like <link href="http://mydomainname/css/sample.css" rel="stylesheet"> and it’s working well (my public folder is on my public_html folder cpanel hosting).

However, i want to use a relative path instead of direct link to my css file. I want to use an easier approach like <link href="css/sample.css" rel="stylesheet">, it works if im working on the root route, but it’s not working when it goes into deeper route of my website.

Can anyone help how to generate the relative path to my css file?

Thank you.

3

Answers


  1. Chosen as BEST ANSWER

    It was solved by modifying vendorlaravelframeworksrcIlluminateFoundationhelpers.php into :

    function asset($path, $secure = null)
    {
        $url = app('url')->asset($path, $secure);
        return parse_url($url, PHP_URL_PATH);
    }
    

    all the asset() code in my laravel now produce only the path (by removing the domain URL) and works either on my production or localhost


  2. This is achievable using the easier approach you suggest, you are just missing one /.

    If you link to your CSS file using a path like this; /css/sample.css then it tells the browser to fetch that document in relation to the root URL. This is the same for any asset you use.

    So as an HTML link it would be:

    <link href="/css/sample.css" rel="stylesheet">
    

    This would tell the browser, no matter what page you are on, to fetch the sample.css file from http(s)://example.com/css/sample.css.

    Without the / at the beginning, your link is saying fetch it in relation to the current page; http(s)://example.com/your/page/url/css/sample.css. On your homepage this will obviously be successful as the URL would still resolve to http(s)://example.com/css/sample.css.

    Login or Signup to reply.
  3. According to this you just need to edit your index.php that located in public folder like below :

    /*
    |--------------------------------------------------------------------------
    | Turn On The Lights
    |--------------------------------------------------------------------------
    |
    | We need to illuminate PHP development, so let us turn on the lights.
    | This bootstraps the framework and gets it ready for use, then it
    | will load up this application so that we can run it and send
    | the responses back to the browser and delight our users.
    |
    */
    
    $app = require_once __DIR__.'/../bootstrap/app.php';
    
    // set the public path to this directory
    $app->bind('path.public', function() {
        return __DIR__;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search