5

I am using Laravel 5 and need to do a wildcard route, sending the user to different controllers based on the URL type, pulled in from the database.

I need to check the URL slug in the database, and then load the relevant controller/method based on the slug type, held in the database. I am struggling with the final part, which is sending the user to the relevant controller. Below is my route:

Route::any('{slug}', function($slug){
    $url = \App\Url_slug::where('url_slug', $slug)->first();
    if($url->count()){
        switch($url->url_type){
            case 'product':
                // SEND USER TO PRODUCT CONTROLLER
                break;
            case 'category':
                // SEND USER TO CATEGORY CONTROLLER
                break;
            case 'page':
                // SEND USER TO PAGE CONTROLLER
                break;
        }
    } else {
        abort(404);
    }
});

What do I need to replace the comments with in order the send the user to the relevant controller?

Mike
  • 8,767
  • 8
  • 49
  • 103

2 Answers2

2

To do this, you need to load an instance of app() and then call make('Controller') method as well as callAction. Full route below:

Route::any('{slug}', function($slug){
    $url = \App\Url_slug::where('url_slug', $slug)->first();
    if($url->count()){
        $app = app();

        switch($url->url_type){
            case 'product':
                $controller = $app->make('App\Http\Controllers\ProductController');
                break;
            case 'category':
                $controller = $app->make('App\Http\Controllers\CategoryController');
                break;
            case 'page':
                $controller = $app->make('App\Http\Controllers\PageController');
                break;
        }
        return $controller->callAction('view', ['url_slug' => $url->url_slug, 'url_slug_id' => $url->id]);
    } else {
        abort(404);
    }
});
geoffs3310
  • 5,599
  • 11
  • 51
  • 104
Mike
  • 8,767
  • 8
  • 49
  • 103
  • 1
    You need to reference the full path to the controllers in order for this to work. I've edited the answer to reflect this. – geoffs3310 Jul 30 '15 at 13:03
1

You can simply resolve a controller instance from the service container, and call methods on that:

return app('App\Http\Controllers\ProductController')->show($product);

This will call the ProductController@show action, pass whatever is in $product as a parameter, and return the rendered Blade template.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201