Laravel 5.6 getRouteKeyName() not working

后端 未结 1 2028
予麋鹿
予麋鹿 2021-01-12 13:45

This is the code I have so far:

Web.php

Route::get(\'/{uri}\', \'PageController@show\')->name(\'page.show\');

PageController

相关标签:
1条回答
  • 2021-01-12 13:56

    You should do something like the following:

    // Route
    Route::get('/{page}', 'PageController@show')->name('page.show');
    
    // Controller Method
    public function show(Page $page)
    {
        return view('templates.page', compact('page'));
    }
    

    If /{page} contains an id like: 1 and your pages table has id column then all done but if you would like to query the pages table other than an id then declare the getRouteKeyName method in your Page model and retuen that column name from that method. So for example, if your pages table has unique slug and your uri has something like example.com/contact then declare the following method:

    public function getRouteKeyName()
    {
        return 'slug'; // db column name
    }
    

    Now, the framework will query for a page using something like where slug = {slug from uri} other than id/default. Hope it helps now.

    0 讨论(0)
提交回复
热议问题