Even though the correct id is set in the href of the anchor tag, my controller takes an id one behind

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

routes/web.php

Route::get('cars', [AppHttpControllersCarsController::class, 'index'])->name('cars');
Route::get('cars/{id}/delete', [AppHttpControllersCarsController::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');
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x