metanerd
metanerd

Reputation: 742

Laravel 5.5 Route model binding with customized key name

I searched a lot of topics related already on SO. I am unable to make it work with the Controller method, but it works when I add it in the route file like this:

Both methods have this in the Application model aka app/Application:

class Application extends Model
{

    public function getRouteKeyName(): string
    {
        return 'token';
    }
    ...

so my routes/web.php, which works, looks like this:

Route::get('/application/{locale}/{application}', function (string $locale, App\Application $application) {
    return view(
        'application.application.main',
        [
            'application' => $application,
            'isLanguageNeeded' => false,
        ]
    );

});


my app/Http/Controllers/ApplicationController.php, which returns an Application not found error, looks like this:

    public function application(string $locale,  \App\Application $application)
{
    return view(
        'application.application.main',
        [
            'application' => $application,
            'isLanguageNeeded' => false,
        ]
    );
}

the routes/web.php:

Route::get('/application/{locale}/{application}', 'ApplicationController@application');

Upvotes: -1

Views: 1035

Answers (2)

Vaggelis Ksps
Vaggelis Ksps

Reputation: 328

Just recreated a project. Used dummy names for methods and other.

In ApplicationsController i added:

`public function index(string $locale, \App\Application $application)
{
  dd('here');
}`

In web routes: Route::get('applications/{locale}/{application}', 'ApplicationsController@index');

In Application model:

public function getRouteKeyName() : string { return 'token'; }

Then php artisan serve and in http://127.0.0.1:8000/applications/el/test1 i got a correct response you can try explicit binding https://laravel.com/docs/5.7/routing#explicit-binding

Also note that 404 response is used when there is no record found. For example if i hadn't an app with test1 token i get 404;

I hope it helps.

Upvotes: 0

Mehrdad Saami
Mehrdad Saami

Reputation: 131

Laravel automaticlly passing request as a first parameter to the controller ... for this reason you should edit your controller like this :

public function application(Illuminate\Http\Request $request ,string  $locale,\App\Application $application)
{
    return view(
      'application.application.main',
    [
        'application' => $application,
        'isLanguageNeeded' => false,
    ]
 );
}

Upvotes: 0

Related Questions