Bojan
Bojan

Reputation: 115

Laravel returns 404 on a edit route (Laravel 6.11.0)

I have created the following route.

Route::resource('admin/products/', 'ProductsController')->middleware('auth');

I've used Artisan to create a controller with all the methods (index, create, edit, etc).

When I use the command php artisan route:list I get the following routes (among others):

GET|HEAD | admin/products/{}/edit | edit | App\Http\Controllers\ProductsController@edit | web,auth|
DELETE | admin/products/{} | destroy| App\Http\Controllers\ProductsController@destroy| web,auth|

Which is to be expected. But when I add {{ route('edit', $product->id) }} to the link href, the link is generated properly, but when I click on it, I get the 404 page. The same is when I use form to post to destroy (I've created a form with action="{{ route('destroy', $product->id) }}" and @method('DELETE') and I still get 404.

Any help where I should start looking for a solution would be appreciated.

Upvotes: 0

Views: 973

Answers (2)

Bojan
Bojan

Reputation: 115

As suggested by Harven, the problem was that the resource route was not defined properly. After removing the backslash, everything started to work:

Route::resource('admin/products', 'ProductsController')->middleware('auth');

After this, the route list was filled properly, and the route name was also properly generated

| GET|HEAD| admin/products/{product}/edit | products.edit | App\Http\Controllers\ProductsController@edit | web,auth |

Upvotes: 0

Emad Ha
Emad Ha

Reputation: 1222

In your code

GET|HEAD  | admin/products/{}/edit

the {} should be filled with a value, something like {item}

If in your controller ProductsController@edit method you have the code like

public function edit(Request $request, Item $item){
}

the second argument Item $item should 1) exist, 2) should match the value you have in your route {variable}, so if you have {item} the variable in the method argument should be item, if it's {something} then it should be public function edit(Request $request, Item $something);...

Note that Request $request, is not required in the method;

I'd like to add that, doing so Item $item will result in 404 if the item is not found, the item will be fetched based on the getRouteKeyName() method in that Item's Model, therefore if you have in your Item model something like

public function getRouteKeyName()
    {
        return 'slug';
    }

The item will be fetched by the slug column from database. again, if you don't have that method used it will use the ID.

So to sum up, the web whould have {some_value} in there matching your controller's argument of that model Product $some_value, where some_value is by default the ID of the Product model unless you're defining the getRouteKeyName() method your Products Eloquent model

Laravel Controllers Dependency Injection Hope that solves it!

Upvotes: 3

Related Questions