Laravel single route point to different controller depending on slugs

Deadly 提交于 2019-12-02 10:44:21

You could call a controller manually inside the route closure. Though I would suggest doing the validation in a helper file to make the route file clean and readable.

Route::group(['middleware' => ['sal', 'menu']], function () {

    Route::get('/{event}/{page}', function($event, $page) {
        // you could do something like
        $user_type = Auth::user()->user_type;
        if($user_type == "organizer")
        {   

            $controller = $app->make('OrganizerController');  
            return $controller->callAction('controllerFunc', $parameters = array());          
        }
        else
        {
           $controller = $app->make('ClientController');  
           return $controller->callAction('controllerFunc', $parameters = array());          
        }        

    });
});

An alternative to the route solution could be to handle the logic in the controller itself:

First, update routes.php to something like:

Route::group(['middleware' => ['sal', 'menu']], function () {
    Route::get('/{event}/{page}', 'RoutesController@index');
});

Then, in the RoutesController.php file (add to app/Http/Controllers), you can do something similar to:

public function index()
{
    $event = Request::segment(1); // get the {event} part of the route
    $page = Request::segment(2); // get the {page} part of the route

    // get event data from database, e.g.
    $event_data = Event::where( 'slug', $event )->first();

    // load correct page
    switch ( $page ) {
        case "people":
            return $this->people();
        break;
        case "anotherPage":
            return $this->another_page();
        break;
    }
}

private function people()
{
    // show view
    return View::make('event.people');
}

This solution keeps your routes file clean, but also lets you handle the different event and page data, and load different views depending on the page being looked at. Your extra logic would be better in a controller rather than the routes file.

It all depends on where you prefer to code your page / view logic. You can use this approach call functions in the same controller, or external ones.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!