I have variable const deleteUrl = "{{ url('ingredients') }}/";
in my index.blade.php
file.
I want to use it in index.js
, but in console I have:
Uncaught (in promise) ReferenceError: deleteUrl is not defined at index-4b1b8432.js:77:27775
What can I do to fix it?
My code:
index.blade.php
:
<x-app-layout>
{{-- another code --}}
</x-app-layout>
<x-slot name="jsFiles">
const deleteUrl = "{{ url('ingredients') }}/";
<script src="{{ asset("js/ingredients/index.js") }}"></script>
</x-slot>
index.js
:
import $ from 'jquery';
$(function() {
console.log(deleteUrl);
};
app.blade.php
:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
<!-- Scripts -->
@vite(['resources/css/app.css', 'resources/js/app.js', 'resources/js/ingredients/index.js'])
</head>
<body class="font-sans antialiased">
<div class="min-h-screen bg-gray-100">
@include('layouts.navigation')
<!-- Page Heading -->
@if (isset($header))
<header class="bg-white shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
{{ $header }}
</div>
</header>
@endif
<!-- Page Content -->
<main>
{{ $slot }}
</main>
</div>
<!-- JS Files -->
{{ $jsFiles ?? '' }}
</body>
</html>
2
Answers
I think
window
global object would work in this case, i had a similar requirement in the past and i have solved it using the same. For e.g in yourindex.blade.php
file assign php variable towindow
object like belowand then in your
index.js
file you can retrieve it fromwindow
global object like belowPS: Dont forget to add
defer
attribute while including this script any where becausedefer
loads the script asynchronously after the HTML content has been parsed so that you can access your variable in window object easily.Change the code from
to
What this does is assign variable
deleteUrl
inside JS and use that same variable to all JS files after declaration.More explanation from other stack overflow answer