user3322389
user3322389

Reputation: 145

How to send PUT request with a file and an array of data in Laravel

I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.

Please see the code below :

web.php ( route )

Route::group(['prefix' => 'api'], function()
{
    Route::put('products/{id}', 'ProductController@update');
});

My angularjs product service :

function update(productId, data, onSuccess, onError){
        var formData = new FormData();
        formData.append('imageFile', data.imageFile);
        formData.append('image', data.image);
        formData.append('name', data.name);
        formData.append('category_id', data.category_id);
        formData.append('price', data.price);
        formData.append('discount', data.discount);
        Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined,   {'Content-Type': undefined}).then(function(response) {

                onSuccess(response);

            }, function(response){

                onError(response);

            }
        );
    }

My ProductController update function

public function update(Request $request, $id) {
// Just print the request data
        dd($request->all());
    }

This is what I see in Chrome inspectmen Put headerSended data Result was empty

Please share your experiences on this problem. Thanks.

Upvotes: 12

Views: 8880

Answers (3)

Yusuf Ibrahim
Yusuf Ibrahim

Reputation: 1619

what you need is Only normal POST request with new field named _method=put then your code will work normally:

enter image description here

Upvotes: 13

Lucio Assis
Lucio Assis

Reputation: 443

You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Try this method:

public update(Request $request, $id)
{
    $request->someVar;
    $request->file('someFile');

    // Get variables into an array.
    $array = $request->all();

Also, make sure you're using Route::put or Route::resource for your route.

Upvotes: 1

Related Questions