Phil_Dr's avatar

Delete route don't work with web.php laravel

Hey!! I'm trying to make delete route in web.php like this:

Route::delete('delete/{id}', [App\Http\Controllers\ProductrsController::class, 'destroy']);

This is the controller destroy method :

public function destroy($id)
    {
        $filepath = 'C:\xampp\htdocs\lec5HW\Products.json';
        $fileContent = file_get_contents($filepath);
        $jsonContent = json_decode($fileContent, true);
        if ($id < 0 || $id > count($jsonContent)) {
            return response()->json(['messege' => 'wrong ID'], 400);
        }
        unset($jsonContent[$id - 1]);
        file_put_contents($filepath, json_encode(array_values($jsonContent)));
        return response()->json(['messege' => 'Product has been deleted successfully', 'data' => $jsonContent], 200);
    }

And I'm getting this error on the browser:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: DELETE.

The same function works on api.php without problems using Postman application. So am I doing something wrong or it's a problem with laravel ??

0 likes
12 replies
Snapey's avatar

the problem is the way you call the route in the browser but you don't show that?

1 like
furqanDev's avatar

@Philip Droubi Paste the code of Blade view file form which you are sending this request. We don't know if you are using just a simple anchor tag <a></a> or a form with GET Request.

1 like
Sinnbeck's avatar

@Philip Droubi That isnt possible. You are expecting a DELETE call, but are your a GET call (call url in the browser). So either use Postman, or do it in code. There is no way of calling a delete route in the url bar in the browser.

2 likes
furqanDev's avatar

@Philip Droubi If you want to do such thing then use GET request and this method is not good in some cases.

But if you want to do it then change the route like.

Route::get('delete/{id}', [App\Http\Controllers\ProductrsController::class, 'destroy']);
1 like
Sinnbeck's avatar

Only use a get route as a test.. Don't do this in production.. It will be way to easy to just post a link on a page that will delete stuff for a user.

2 likes
Asaad Belkahia's avatar

Hello,

we need to see the view (blade) code for detect where is exactly the issue, or please try with this code for calling destroy method :

< form method="post" action="{{route('products.destroy',$product->id)}}"> @method('delete') @csrf < button type="submit" class="btn btn-danger btn-sm">Delete< /button >

2 likes
Asaad Belkahia's avatar

Please try with this code in web.php : Route::delete('/products/{id}', [\App\Http\Controllers\ProductrsController::class, 'destroy']) ->name('products.destroy');

i hope if that can help you.

2 likes

Please or to participate in this conversation.