4
votes

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?

1
I get exactly the same results. The command automatically injects $sku, which doesn't work but renaming it to $skus works. Seems like a bug. - DevK
Thanks. I was able to get it working with Route::resource('skus', 'SkusController')->parameters(['skus' => 'sku']);, but I'll still report it as an issue on Github. - flyingL123
Laravel uses the Doctrine Inflector for pluralization, you can file issues against that for unintended results. - sam
Laravel always recommends using singular model names for Route::resource, and it will handle the pluralization automagically for you - Ohgodwhy
@Ohgodwhy Is that true though? Let alone that having resources prefixed with the plural version seems more intuitive and more common in APIs, the documentation also seems to use pluralized prefixes most of the time. - DevK

1 Answers

6
votes

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.