【问题标题】:How to handle dynamic urls that are at the same level in Laravel 4?如何处理 Laravel 4 中同一级别的动态 url?
【发布时间】:2013-12-02 04:54:40
【问题描述】:

我希望在同一 url 级别访问两种类型的内容。

  1. 页面
    • mysite.com/about
    • mysite.com/contact
  2. 类别
    • mysite.com/category-1
    • mysite.com/category-2

我想根据特定的内容类型路由到控制器的方法。知道我该如何处理吗?

我的代码...

Route::get('{slug}', function($slug) {

    $p = Page::where('slug', $slug)->first();

    if (!is_null($p)) {

        // How i can call a controller method here?

    } else {

        $c = Category::where('slug', $slug)->first();

        if (!is_null($c)) {

            // How i can call a another controller method here?

        } else {

            // Call 404 View...

        }
    }
});

【问题讨论】:

    标签: php laravel laravel-4 laravel-routing


    【解决方案1】:

    不要让你的路由文件过于复杂,你可以创建一个控制器来为你处理这一切:

    你的蛞蝓路线:

    Route::get('{slug}', 'SlugController@call');
    

    一个 SlugController 来处理你的调用:

    class SlugController extends Controller {
    
        public function call($slug)
        {
            $p = Page::where('slug', $slug)->first();
    
            if (!is_null($p)) {
    
                return $this->processPage($p);
    
            } else {
    
                $c = Category::where('slug', $slug)->first();
    
                if (!is_null($c)) {
    
                    return $this->processCategory($c);
    
                } else {
    
                    App::abort(404);
    
                }
            }
        }   
    
        private function processPage($p)
        {
            /// do whatever you need to do
        }
    
        private function processCategory($c)
        {
            /// do whatever you need to do
        }
    }
    

    【讨论】:

    • 感谢您的回复安东尼奥。在看到你的答案之前,我最终做了你给出的相同的解决方案,完全按照你的建议去做。有了这个,我相信这应该是处理这个问题的最好和最直观的方法。我最初尝试做的是保留控制器的上下文。就我而言,我有一个名为 GameController 的控制器,它处理与游戏相关的所有方法。使用此解决方案,我最终会将类别排除在此控制器之外,但正如您所说,路线最终变得不那么复杂,这是一件好事。
    猜你喜欢
    • 2019-03-19
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多