In my routes files I have a bunch or routes for testing purposes:
/** testing controllers */
Route::get('viewemail', 'TestController@viewemail');
Route::get('restore', 'TestController@restore');
Route::get('sendemail', 'TestController@send_email');
Route::get('socket', 'TestController@socket');
Route::get('colors', 'TestController@colors');
Route::get('view', 'TestController@view_test');
Route::get('numbers', 'TestController@numbers');
Route::get('ncf', 'TestController@ncf');
Route::get('dates', 'TestController@dates');
Route::get('print', 'TestController@printer');
Route::get('{variable}', 'TestController@execute');
/** End of testing controllers */
I want to eliminate all those routes and simple use the name of the given URL to call and return the method:
I have accomplished that in this way:
Route::get('{variable}', 'TestController@execute');
And in my testing controller:
public function execute($method){
return $this->$method();
}
Basically what I want to know if Laravel has a built in solution to do this, I was reading the documentation but couldn't find any way to accomplish this.
From official documentation: http://laravel.com/docs/5.1/controllers#implicit-controllers
Laravel allows you to easily define a single route to handle every action in a controller class. First, define the route using the
Route::controller
method. The controller method accepts two arguments. The first is the base URI the controller handles, while the second is the class name of the controller:Route::controller('users', 'UserController');
Next, just add methods to your controller. The method names should begin with the HTTP verb they respond to followed by the title case version of the URI:
<?php namespace App\Http\Controllers; class UserController extends Controller { /** * Responds to requests to GET /users */ public function getIndex() { // } /** * Responds to requests to GET /users/show/1 */ public function getShow($id) { // } /** * Responds to requests to GET /users/admin-profile */ public function getAdminProfile() { // } /** * Responds to requests to POST /users/profile */ public function postProfile() { // } }
As you can see in the example above, index methods will respond to the root URI handled by the controller, which, in this case, is users.
You could add a route pattern for the endpoints you want to listen for. Route them to a controller action, and then inspect the request:
class TestController extends Controller
{
public function handle(Request $request)
{
$method = $request->segment(1); // Gets first segment of URI
// Do something…
}
}
And in your route service provider:
$router->pattern('{variable}', 'foo|bar|qux|baz');