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');
}
-
Content-Type
header and its value set toapplication/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>
-
storefront
is a Blade view and is stored asstorefront.blade.php
console.log('works')
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.
Top comments (1)
Excelente!!
To maintain javascript synthase start your code with
<br> </code><br> and then remove in controller:</p> <p><code><br> $view = view('service-worker');<br> $remove = str_replace('<script>', '', $view);<br> return response($remove)->header('Content-Type', 'application/javascript');<br> </code></p>