Laravel 5条件路由和多控制器


Laravel 5 conditional routing and multiple controllers

基本上我的应用程序有两种类型的动态url。

  1. app.com/{页面}
  2. <
  3. app.com/{user}/gh>

都有自己的控制器

  1. PageController@index
  2. 用户' ProfileController@index

但我正在努力使它工作。

我已经尝试了几种不同的方法。以下是我试过的两种。

Route::get('{slug}', function($slug) {
    if (App'Page::where('slug', $slug)->count()) {
        // return redirect()->action('PageController@index', [$slug]);
        // return App::make('App'Http'Controllers'PageController', [$slug])->index();
        return 'Page found';
    } else if (App'User::where('username', $slug)->count()) {
        // return redirect()->action('User'ProfileController@index', [$slug]);
        // return App::make('App'Http'Controllers'User'ProfileController', [$slug])->index();
        return 'User found';
    } else {
        return abort(404);
    }
});

我觉得我应该对中间件/过滤器这样做。任何帮助都太好了。谢谢。

我认为您可以使用中间件来过滤Route::group,如果它是页面或用户。

Route::group(['middleware' => 'isPage'], function () {
    Route::get('{slug}', ['as'=> 'pages.show', 'uses' => 'PageController@show']);
});
Route::group(['middleware' => 'isUser'], function () {
    Route::get('{slug}', ['as'=> 'users.show', 'uses' => 'User'ProfileController@show']);
});

如果您对Pages使用slugs而对Users使用id,那么您处理问题的想法可能更有意义,但是由于您对页面和用户都使用了slugs,我强烈建议您尝试不同的方法。为什么不声明两条路由呢?为什么不使用相应控制器的"show"方法,并与资源约定保持一致呢?

Route::get('pages/{slug}', ['as'=> 'pages.show', 'uses' => 'PageController@show']);
Route::get('users/{slug}', ['as'=> 'users.show', 'uses' => 'User'ProfileController@show']);

如果你真的想保留你的"root-slug- respectredirect "功能,你可以在后面写:

Route::get('{slug}', function($slug) {
    if (App'Page::where('slug', $slug)->count()) {
        return redirect(route('pages.show', $slug));
    } else if (App'User::where('username', $slug)->count()) {
        return redirect(route('users.show', $slug));
    }
    return abort(404);
});

我不建议这样做,因为这似乎是浪费查询。

这里是关于Laravel RESTful资源控制器的文档。