Route resource destroy not working laravel

All we need is an easy explanation of the problem, so here it is.

I have a user_transaction table and I am trying to delete a record in the table but I am not successful.

UserTransaction.php

protected $table = 'user_transaction';

blade

<form action="{{ route('transactions.destroy', $transaction->id) }}" method="post" >
    @method('delete')
    @csrf
    <button type="submit" class="btn btn-default p-0">
        <i class="ft-trash-2 text-grey font-medium-5 font-weight-normal"></i>
    </button>
</form>

web.php

Route::resource('transactions', 'Admin\TransactionController');

TransactionController.php

public function destroy(UserTransaction $userTransaction)
{
    dd($userTransaction->id);
    $userTransaction->delete();
    return redirect()->route('transactions.index');
}

This code show null

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The likely cause of this is a naming mismatch between your resource route parameter and the name of the variable used in your resource controller for route model binding.

By default resource routes use the singlar of the resource you provide in the route definition as the route parameter. So in your example:

Route::resource('transactions', 'Admin\TransactionController');

The above will produce some routes like the following:

GET|HEAD  | /transactions/{transaction}
DELETE    | /transactions/{transaction}
GET|HEAD  | /transactions/{transaction}/edit

For route model binding to work, the route parameter name and the name of the variable used in your controller need to match.

So what you need to do is change the name of the variable used in your controller:

public function destroy(UserTransaction $transaction)
{
    dd($transaction->id);
    $transaction->delete();
    return redirect()->route('transactions.index');
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

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

Leave a Reply