Search code examples
laravelrequestnuxt.js

Laravel PUT/PATCH returns 302 Found and redirects to frontend URL


1.) Having a Laravel route inside api.php:

Route::group(['prefix' => 'admin'], function() {
    Route::group(['prefix' => 'images'], function() {
        Route::put('/{image}', [\App\Http\Controllers\ImagesController::class, 'update']);
    });
});

Update method code:

public function update(Image $image, ImageData $data) {
    $image->update([
        'title' => $data->title,
        'source' => $data->source
    ]);
    return response('', 200);
}

2.) Nuxt:

export const useApiFetch = async <T>(request, opts?) => {
    const config = useRuntimeConfig()
    return useFetch<T>(request, {baseURL: config.public.apiBase, ...opts})
}

Component

const finishEditing = async () => {
    await useApiFetch(`admin/images/${image.id}`, {
        method: 'PUT',
        data: props.image
    })
    store.editingTitle = false
    store.editingSource = false
}

When sending PUT or PATCH request, it returns 302 Found and redirects to localhost:3000, which is the address for frontend. Why does this happens? Middleware setup for api routes is out-of-the-box.


Solution

  • I met similar issue before and it happens when the request is not authenticated. You need to check your request is sent to controller correctly.

    Maybe your request would be cut off in the middleware or something else like csrf.