DEV Community

Zubair Mohsin
Zubair Mohsin

Posted on

Return JavaScript from Laravel controller method

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.

Latest comments (1)

Collapse
 
naldoalmeida profile image
Naldo • Edited

Excelente!!
To maintain javascript synthase start your code with


<br> </code><br> and then remove in controller:</p> <p><code><br> $view = view(&#39;service-worker&#39;);<br> $remove = str_replace(&#39;<script>&#39;, &#39;&#39;, $view);<br> return response($remove)-&gt;header(&#39;Content-Type&#39;, &#39;application/javascript&#39;);<br> </code></p>