How can I use routes / wildcards in Laravel?

I am using Laravel 5 and you need to make a wildcard pattern by sending the user to different controllers based on the type of URL pulled from the database.

I need to check the URL pool in the database and then load the appropriate controller / method based on the slug type stored in the database. I am struggling with the last part, which sends the user to the appropriate 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 comments in order to send the user to the appropriate controller?

+5
source share
2 answers

To do this, you need to load the instance of app() , and then call the 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); } }); 
+2
source

You can simply resolve the controller instance from the service container and call the methods:

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

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

+1
source

All Articles