Laravel File Updates: Understanding POST vs PUT and the _method Field

5 min readUpdated on

When you update a record with a file upload in Laravel and Inertia.js, you send POST with _method: "PUT" instead of a real PUT. Here is why, and how to implement it.

The Problem: HTTP Methods and File Uploads

Understanding HTTP Methods

In RESTful APIs, different HTTP methods serve specific purposes:

  • GET - Retrieve data
  • POST - Create new resources
  • PUT - Update existing resources (complete replacement)
  • PATCH - Partial updates
  • DELETE - Remove resources

An update should be a PUT or PATCH. With files it can’t be.

The File Upload Limitation

  1. POST requests can handle multipart/form-data encoding, which is required for file uploads
  2. PUT requests with multipart/form-data are not parsed by PHP itself: before PHP 8.4, $_POST and $_FILES were only populated for POST, so a multipart PUT or PATCH arrived with an empty body (current Symfony on PHP 8.4+ parses it, but you cannot rely on that in every environment)
  3. HTML forms can only submit GET and POST

The Solution: Method Spoofing

Laravel handles this with “method spoofing” through the _method field.

How Method Spoofing Works

javascript
// Instead of this (multipart PUT is not parsed on older PHP/Symfony setups):
router.put('/posts/1', {
    title: 'Updated Title',
    content: 'Updated content',
    image: fileObject // May arrive empty
});

// We use this:
router.post('/posts/1', {
    _method: 'PUT',
    title: 'Updated Title', 
    content: 'Updated content',
    image: fileObject // This works!
});

Laravel’s middleware intercepts the _method field and treats the request as if it were sent with the specified HTTP method.

Implementation Examples

Create Operation (Standard POST)

Frontend (React with Inertia.js):

jsx
import { useForm } from '@inertiajs/react';

function CreatePost() {
    const { data, setData, post, processing, errors } = useForm({
        title: '',
        content: '',
        image: null,
    });

    const handleSubmit = (e) => {
        e.preventDefault();
        
        post('/posts', {
            forceFormData: true, // Ensures multipart/form-data
        });
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                value={data.title}
                onChange={e => setData('title', e.target.value)}
                placeholder="Title"
            />
            
            <textarea
                value={data.content}
                onChange={e => setData('content', e.target.value)}
                placeholder="Content"
            />
            
            <input
                type="file"
                onChange={e => setData('image', e.target.files[0])}
            />
            
            <button type="submit" disabled={processing}>
                Create Post
            </button>
        </form>
    );
}

Backend (Laravel Controller):

php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $validated['image'] = $request->file('image')->store('posts', 'public');
        }

        Post::create($validated);

        return redirect()->route('posts.index')
            ->with('success', 'Post created successfully!');
    }
}

Update Operation (POST with _method: PUT)

Frontend (React with Inertia.js):

jsx
import { useForm } from '@inertiajs/react';

function EditPost({ post }) {
    const { data, setData, post: submit, processing, errors } = useForm({
        title: post.title,
        content: post.content,
        image: null,
        _method: 'PUT', // This is crucial!
    });

    const handleSubmit = (e) => {
        e.preventDefault();
        
        // Note: We use POST here, not PUT
        submit(`/posts/${post.id}`, {
            forceFormData: true,
        });
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                value={data.title}
                onChange={e => setData('title', e.target.value)}
                placeholder="Title"
            />
            
            <textarea
                value={data.content}
                onChange={e => setData('content', e.target.value)}
                placeholder="Content"
            />
            
            <input
                type="file"
                onChange={e => setData('image', e.target.files[0])}
            />
            
            {post.image && (
                <div>
                    <p>Current image:</p>
                    <img src={`/storage/${post.image}`} alt="Current" width="200" />
                </div>
            )}
            
            <button type="submit" disabled={processing}>
                Update Post
            </button>
        </form>
    );
}

Backend (Laravel Controller):

php
use Illuminate\Support\Facades\Storage;

public function update(Request $request, Post $post)
{
    $validated = $request->validate([
        'title' => 'required|string|max:255',
        'content' => 'required|string',
        'image' => 'nullable|image|max:2048',
    ]);

    // Handle file upload
    if ($request->hasFile('image')) {
        // Delete old image if exists
        if ($post->image) {
            Storage::disk('public')->delete($post->image);
        }
        
        $validated['image'] = $request->file('image')->store('posts', 'public');
    } else {
        // Inertia sends an empty "image" field, which would overwrite the column with null
        unset($validated['image']);
    }

    $post->update($validated);

    return redirect()->route('posts.index')
        ->with('success', 'Post updated successfully!');
}

Routes (web.php):

php
Route::resource('posts', PostController::class);

Key Differences Between Create and Update

AspectCreate (POST)Update (POST + _method: PUT)
HTTP MethodPOSTPOST (with _method: 'PUT')
Route/posts/posts/{id}
Form DataStandard fieldsStandard fields + _method
Laravel Methodstore()update()
PurposeCreate new resourceUpdate existing resource

Important Configuration Notes

1. Inertia.js Configuration

Inertia switches to multipart/form-data on its own when the data contains a File, but forceFormData: true makes it explicit and also covers the case where no file is selected:

javascript
submit(`/posts/${post.id}`, {
    forceFormData: true, // This ensures proper multipart encoding
});

2. File Validation

Validate type and size of every upload:

php
$request->validate([
    'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
]);

Common Pitfalls and Solutions

Pitfall 1: Using Actual PUT Request for Files

javascript
// ❌ Multipart PUT is not parsed on older PHP/Symfony setups
router.put('/posts/1', formData);

// ✅ Use this instead
router.post('/posts/1', {
    ...formData,
    _method: 'PUT'
});

Pitfall 2: Forgetting forceFormData

javascript
// ❌ Relies on Inertia detecting the File object; with no file selected the payload is sent as JSON
submit(`/posts/${post.id}`);

// ✅ Be explicit with forceFormData
submit(`/posts/${post.id}`, {
    forceFormData: true
});

Pitfall 3: Not Handling Existing Files

php
// ❌ This will lose the existing image if no new one is uploaded
// ($rules includes 'image' => 'nullable|image|max:2048')
public function update(Request $request, Post $post)
{
    $post->update($request->validate($rules));
}

// ✅ Handle file updates properly
public function update(Request $request, Post $post)
{
    $validated = $request->validate($rules);
    
    if ($request->hasFile('image')) {
        // Delete old image
        if ($post->image) {
            Storage::disk('public')->delete($post->image);
        }
        $validated['image'] = $request->file('image')->store('posts', 'public');
    } else {
        unset($validated['image']);
    }
    
    $post->update($validated);
}

Conclusion

For file uploads in updates, send POST with _method: "PUT" and forceFormData: true. The spoofed method still hits update() on your resource controller, so routing stays unchanged.

Related articles

Existing system support

Need help with a live application?

I help companies improve live systems, clean up delivery workflows, and ship new features without adding avoidable complexity.

Comments (0)
Sign in to leave a comment

You need to be signed in to add a comment.

Login

Need someone to take responsibility for the next step?

Let’s talk about your project and define a scope that actually makes sense for your goals.