dongyiyu882684 2015-10-09 08:31
浏览 57

Laravel 5条件路由和多个控制器

So basically my app has two types of dynamic url..

  1. app.com/{page}
  2. app.com/{user}

Both having their own controllers

  1. PageController@index
  2. User\ProfileController@index

But I'm struggling to get this working.

I have tried a few different methods. Here are two I have tried..

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);
    }
});

I feel I should be doing this with middleware/filters. Any help would be great. Thanks.

  • 写回答

2条回答 默认 最新

  • dongpu9852 2015-10-09 09:08
    关注

    If you were using slugs for the Pages and ids for the Users, your idea of handling the issue might make more sense, but since you are using slugs for both the pages and the users, I strongly suggest you try a different approach. Why not declare two routes? Why not use the "show" methods of the respective controllers while you are at it, and keep in line with conventions for resources?

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

    And if you really want to keep your "root-slug-respective-redirect" functionality you could write afterwards:

    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);
    });
    

    I do advise against it though, as it seems like a waste of queries.

    Here are the docs on Laravel RESTful resource controllers for good measure.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题