Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel resource route being assigned incorrect parameter name

Tags:

php

laravel

Using Laravel 5.6, I'm generating a resource controller with the following command:

php artisan make:controller SkusController --resource --model=Sku

The generated controller file has correctly type-hinted methods. For example:

<?php

namespace App\Http\Controllers;

use App\Sku;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SkusController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @param  \App\Sku  $sku
     * @return \Illuminate\Http\Response
     */
    public function show(Sku $sku)
    {
        //
    }
}

Now, I add a resource route to my routes file, like this:

Route::resource('skus', 'SkusController');

However, in my routes list, the named parameter in these routes is appearing as skus, not sku, causing the route-model binding not to work. The $sku variable in the controller methods turns out empty.

For example, here's the URI for the show methods entry in the php artisan route:list output:

skus/{skus}

Alternatively, I followed the same process for a products resource, and the URI is correct:

products/{product}

In that case the route-model binding works as expected since the controller variable is called $product.

I think I can manually change the parameter name, but I'm just wondering why that should be necessary. Shouldn't the route be generated correctly in the first place?

like image 784
flyingL123 Avatar asked Mar 06 '23 08:03

flyingL123


1 Answers

You can use it like:

Route::resource('skus', 'SkusController')->parameters(['skus' => 'sku']);

It can be used in Route model binding. like

public function update(Request $request, Sku $sku)
    {
        $sku->update(); // data to be updated
    }

where Sku will be your Model name.

like image 168
Satendra Rawat Avatar answered Apr 07 '23 01:04

Satendra Rawat