Home > Back-end >  Even though the correct id is set in the href of the anchor tag, my controller takes an id one behin
Even though the correct id is set in the href of the anchor tag, my controller takes an id one behin

Time:09-16

What I have

blade.php file

<form action="cars/{{ $car->id }}" method="POST" class="pt-3">
    @csrf
    @method('delete')
    <button 
        type="submit"
        class="border-b-2 pb-2 border-dotted italc text-red-500"
    >
        Delete &rarr;
    </button>
</form>

Controller in Laravel

public function destroy($id)
{
    $car = Car::find($id)->first();

    $car->delete();

    return redirect('/cars');
}

Problem

The above controller, always deletes the record in the db that is one id behind. For example, if the id sent in the request is 14, the controller deletes the record with the id of 13.

Two other important details that relates to this question that I want to mention is,

-> I have double checked the url that the request is sent to and the url holds the correct id. So it has to be the controller that fails.
-> Even though the above code for the controller does not work, the following code works perfectly fine.

   public function destroy(Car $car)
{
    $car->delete();

    return redirect('/cars');
}

I can not figure out why the code I have typed under "Controller in Laravel" does not work while the code I have typed directly above this works.

CodePudding user response:

routes/web.php

Route::get('cars', [App\Http\Controllers\CarsController::class, 'index'])->name('cars');
Route::get('cars/{id}/delete', [App\Http\Controllers\CarsController::class, 'destroy'])->name('cars.destroy');

blade.php file

I did added form action in route.

<form action="{{route('cars.destroy', $car->id)}}" method="POST" class="pt-3">
    @csrf
    @method('DELETE')
    <button type="submit" class="border-b-2 pb-2 border-dotted italc text-red-500"> Delete &rarr;</button>
</form>

Controller file

Replace find to findOrFail and remove first(). and last get id using $request->id.

public function destroy(Request $request) {
    $car = Car::findOrFail($request->id);
    $car->delete();
    return redirect()->route('cars');
}
  • Related