In the javascript of my blade view I have:
$('#miSelector').on('change', function () {
// .... Más código
if (condicion) {
$('#miFormulario').prop('action', "{{ route('nombre_de_ruta') }}");
} else {
$('#miFormulario').prop('action', "{{ route('otro_nombre_de_ruta') }}");
}
$('#miFormulario').submit();
});
This works perfectly. When the event fires, it chooses the appropriate route, and the form is directed to the desired controller.
The problem comes when I put this javascript in an external file, in public/js
, and call it from the blade, with the helper asset()
, like this:
<script language="javascript" src="{{ asset('js/mi_script.js') }}"></script>
All the script works fine (I have set console.log
to see the status of the variables, and trace everything), except the helper route()
, which can no longer resolve the route, and generates some characters that "corrupt" the URL, leading to a 404. I have tried substituting
"{{ route('otro_nombre_de_ruta') }}"
by
"{!! route('otro_nombre_de_ruta') !!}"
but it doesn't work either.
This happens to me in both cases (if the conditional is met, or not). It's as if the helper route()
can't work on external scripts that are imported into the view, but has to be physically inside the view.
Is there a solution, or am I focusing the approach wrong? In any case, if you could give me a clear and detailed answer (I'm still very new to Laravel), I'd really appreciate it.
You are confusing the processing on the server and on the client (browser in this case):
When you call an external JavaScript file (in this case), Laravel doesn't read it or import it or the like, since you're already in the browser, what you do with the helper
asset()
is simply define the path of the external file.Your file
mi_script.js
is interpreted by the browser like any other JavaScript file on any website, and therefore will never "find" the Laravel path.Solutions
First of all, Laravel isn't designed to work that way, it's out of its league.
Depending on how your application is designed, you can either use Laroute to make your routes available in JavaScript (but be aware of which routes you enable), or you can figure out how to return that section of JavaScript to your blade view. There are a few other solutions but they all turn out to be external to Laravel.