1

我有两种类型的内容,我希望它们可以在相同的 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...

        }
    }
});
4

1 回答 1

3

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

你的蛞蝓路线:

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
    }
}
于 2013-11-18T22:09:23.373 回答