DEV Community

Zubair Mohsin
Zubair Mohsin

Posted on

6 1

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top 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>

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay