Question

I have two types of content that I would like them to be accessed at the same url level.

  1. Page:
    • mysite.com/about
    • mysite.com/contact
  2. Category:
    • mysite.com/category-1
    • mysite.com/category-2

I would like to route to a method of a controller according to the specific type of content. Any idea how can I handle this?

My code...

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

        }
    }
});
Was it helpful?

Solution

Don't overcomplicate your routes file, you can create one controller to handle it all for you:

Your slug route:

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

A SlugController to handle your calls:

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
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top