skip to Main Content

I am trying to send ID of record to resource controller for edit through AJAX request in Laravel. My code is like below.

function editdetails(id) {
              $.ajax({
                type:'GET',
                url:"{{ route('users.edit', id ) }}",
                success:function(data){
                  console.log(data);
                }
              });
            }

But I am getting error like below.

Use of undefined constant id - assumed 'id' (this will throw an Error in a future version of PHP) 

2

Answers


  1. Since you are using javascript here, you can’t use blade syntax. In order to achieve this, you either have to use URL as a string that you defined in your routes file:

    url: "/your/url/" + id 
    //or
    url: `/your/url/${id}`
    

    or you can save your route in some hidden element on you page and use it in js, for example:

    //define in blade file
    <input type="hidden" id="edit-url" value="{{route('users.edit', $id )}}">
       
    //use in js file
    let url = $('#edit-url').val()
    url: url
    
    Login or Signup to reply.
  2. You can use like this:

    var id = id;
    var url = "{{ route('users.edit',":id") }}";
    url = url.replace(':id', id);
    

    As in your code:
    Replace this:

    function editdetails(id) {
          var id = id;
          var url = "{{ route('users.edit',":id") }}";
          url = url.replace(':id', id);
    
                  $.ajax({
                    type:'GET',
                    url: url,
                    success:function(data){
                      console.log(data);
                    }
                  });
                }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search