loading...

Return JavaScript from Laravel controller method

zubairmohsin33 profile image Zubair Mohsin ・1 min read

If you want to return some JavaScript code from your Laravel controller method, you can do so just by setting a header like below:

public function show()
{
    return response()->view('storefront')
            ->header('Content-Type', 'application/javascript');
}
Enter fullscreen mode Exit fullscreen mode
  • Content-Type header and its value set to application/javascript.
  • You can then use it by specifying the Route URI from web.php file, like below:
<script src="https://example.com/storefront/script"></script>
Enter fullscreen mode Exit fullscreen mode
  • storefront is a Blade view and is stored as storefront.blade.php
console.log('works')
Enter fullscreen mode Exit fullscreen mode

Few thoughts on it

  • There is a trade-off that you loose JavaScript syntax highlight and linting. But, you get dynamic values from database which will be filled for you before outputting this JavaScript.
  • Otherwise you will need to make Ajax request to fetch them.

Practical use-case for this

When we are loading the script registered via Shopify ScriptTag API on shop storefronts, we want our script to already have values from database for that specific shop.

Discussion

pic
Editor guide