Problems converting javascript variable to transfer on an Laravel route

Asked

Viewed 287 times

-2

I am having trouble passing a Javascript variable into a Laravel route. To do so, I am using an AJAX request. The code I’m using is just below:

            $.ajax({
                url: 'rota/emails/'+p.id,
                type: "GET",
                data : {"_token":"{{ csrf_token() }}"},
                dataType: "json",
                success:function(data) {
                  if(data){ 
                    $.each(data, function(key, value){
                      $('#received-emails').append('<div class="text-center">' + value.email+ '</div><a class="btn btn-danger" href="{{route("rota.delete", '+value.id+')}}"><span class="fa fa-user-times"></span></a>'); //o problema esta nesta linha
                    });

                  }
                }
              });

In the use of id #received-emails, i add the Divs with the respective HTML shown above. O value.email works properly, ja the value.id no. in my controller, the id is received as +value.id+ and not as their id which is being acquired by AJAX.

At first I’m trying to create a simple button that when clicking on it, is redirected to a route from Laravel where this is the delete feature. As the example below:

<a href="{{route('rota.delete', id)}}"></a>

I ended up building something like this inside the append:

'<a class="btn btn-danger" href="{{route("rota.delete", '+value.id+')}}"><span class="fa fa-user-times"></span></a>'

What can be the solution to this problem?

  • Switch to href="{{route("rota.delete", value.id)}}"

  • an error such as: Use of Undefined Constant value - assumed 'value' (this will throw an Error in a Future version of PHP)

1 answer

2


This is not possible because Laravel works in the back end. The Laravel Blade Template compiles the view and will execute the route() function and return the route url even before generating the HTML that will be sent to the client. i.e., it will compile the route() function before executing any javascript. Therefore this is not possible. ( But I know some "gambiarras" that solve this.

Instead of putting

route("rota.delete", 'value.id')

Use

var url = "{{ route('rota.delete', ['id' => ':id']) }}"; // isso vai compilar o blade com o id sendo uma string ":id" e, no javascript, atribuir ela a uma variável .

url = url.replace(":id", value.id); // isso vai corrigir a string gerada com o id correto.

console.log(url); // isso vai mostrar a url gerada. Aí a lógica é com você.

I hope I’ve helped!

  • Thank you very much, solved my problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.