如何处理Laravel 4中处于同一级别的动态URL?

时间:2013-11-18 21:10:20

标签: php laravel laravel-4 laravel-routing

我有两种类型的内容,我希望它们可以在同一个网址级别访问。

  1. 网页
    • mysite.com/about
    • mysite.com/contact
  2. 类别
    • mysite.com/category-1
    • mysite.com/category-2
  3. 我想根据特定内容类型路由到控制器的方法。知道怎么处理这个?

    我的代码......

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

1 个答案:

答案 0 :(得分:3)

不要过度复杂你的路线文件,你可以创建一个控制器来为你处理它:

你的slug路线:

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