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.

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

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>

AWS Security LIVE! Stream

Go beyond the firewall

There's more to security than code. Explore solutions, strategies, and the full story on AWS Security LIVE!

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay