Question

I'm having a hard time with sending REST requests with $resource to Laravel application. First of all, $resource POST method sendes Request Payload, which I am unable to read in Laravel, so I had to transform request to send x-www-form-urlencoded instead, and I had to put a function which serializes data in that format. Why isn't this by default?

Another problem is the PUT method, this time in Laravel. I found out that Laravel RESTful controllers don't support PUT methods. Instead, I should send POST request and include _method: 'PUT' as a parameter. Here is the improvised code:

factory('User',function($resource){
    return $resource(apiPath + 'user/:id', {}, {
        update: {
            method: 'POST', 
            params: {id: '@id'}, 
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
            transformRequest: transform()
        }
    })
}

Now if I want to send a PUT request, I have to do something like this:

var userData = {id: 1, firstName: 'John', lastName: 'Doe'};
userData._method = 'PUT';
User.update(userData);

So instead of setting _method to 'PUT' each time manually when I want to make a PUT request, is there any way to make it default? Or, am I doing something wrong, is there a better way to do this? I really don't understand the whole REST thing, what's the point if it's not well supported (Laravel)?. Twitter API also only uses POST and GET. Please correct me if I'm wrong. Thanks.

Was it helpful?

Solution

Try this way:

update: {
    method: 'POST', 
    params: {id: '@id'}, 
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(data){
        data._method = 'PUT';
        return data;
    }
}

OTHER TIPS

Only this method worked for me...

'update': {
                    url:  'urlTOApi/product/:id' + '?_method=PUT',
                    method: 'POST',
                    params: {id: '@id'},
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                },
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top