Laravel 将两条路线结合起来得到简单的 url

Laravel combine two route to have simple url

在 laravel 我有这条路线:

Route::get('/', 'HomeController@index')->name('home');
Route::get('/showContent/{content}', 'HomeController@showContent');

第一个用于显示主页,第二个代码用于显示单个 post,现在我正在尝试将它们组合成一条路线:

Route::get('/{content?}', 'HomeController@index')->name('home');

如果 content 不为空,Web 应用程序必须显示单个 post 否则像使用此控制器一样显示主页

public function index($slug)
{
    if ($slug != null) {
        $this->showContent($slug);
    } else {
        return view('layouts.frontend.content');
    }
}

但是 index 函数出现错误,我该如何解决?

您需要在方法签名中将 $slug 的默认值设置为 null,如下所示:

public function index($slug = null)
{
    if ($slug != null) {
        $this->showContent($slug);
    } else {
        return view('layouts.frontend.content');
    }
}

这允许参数在控制器端是可选的,因为 Laravel 路由器在访问根 /.

时将调用不带任何参数的控制器操作方法

You should keep in mind that defining a route as /{parameter?} is essentially a catch all, meaning any URL that does not match another route definition or is not a physical file on disk will be a match to this route (e.g. /foo, /bar, etc.), so take that into consideration when choosing this approach, as you'll always be executing the showContent() part for unmatched URLs.

您可以在函数参数

中将 null 指定为默认值
  public function index($slug=null)
  {
     if (!$slug) {
         return view('layouts.frontend.content');
     }
     $this->showContent($slug);
  }