tria
tria

Reputation: 33

Change PUT request to POST request to include image update

I wrote a post edit method which at first consisted only of text. I did the update using a PUT request.

Now I want to include images to my posts, so I added it, and it works for my POST request of creating a post but doesn't work for my update post, when I want to change image, since PUT request doesn't support file uploads.

So now I'm stuck trying to change my update method from PUT request that only updates text to a POST request that updates both the text and an image if supplied.

This is the code I wrote so far:

public function update(Request $request, Post $post)
{
    //store updated image
    if($request->hasFile('image') && $request->file('image')->isValid()){
        if($post->hasMedia('posts')) {
            $post->media()->delete();
        }
        $post->addMediaFromRequest('image')->toMediaCollection('post', 's3');
    }
    $post->update(request()->validate([
        'body' => 'required'
    ]));
    return redirect($post->path());
}

I think that the $post->update doesn't work for the POST request. I just want to update a text if an update was given.

Using Laravel 6.

EDIT: My form layout structure (simplified)

<form action="action="/posts/{post}" method="POST">
    @method('PUT')
    @csrf
    <div class="form-group row">
        <input id="body" type="text" class="form-control" name="body" value="{{ old('body', $post->body) }}">
        <input id="image" type="file" class="form-control" name="image">
        <button type="submit" class="btn btn-primary">Update Post</button>
</form>

My routes:

Route::get('/posts/{post}/edit', 'PostsController@edit')->name('posts.edit');
Route::put('/posts/{post}', 'PostsController@update');

Upvotes: 0

Views: 1233

Answers (1)

rahul.sharma
rahul.sharma

Reputation: 467

I tried your code and it worked fine with me , only added @csrf in form tag.

<form action="/posts/{post}" method="POST" enctype="multipart/form-data">
    @csrf
    @method('PUT')
<div class="form-group row">
 <input id="body" type="text" class="form-control" name="body" value="{{ old('body', $post->body) }}">

<input id="image" type="file" class="form-control" name="image">
<button type="submit" class="btn btn-primary">Update Post</button>
</form>

 As you can see i am getting the proper dump for PUT request

Upvotes: 2

Related Questions