How to create a common routing rule in laravel 5.1?

1.8k Views Asked by At

I am new in laravel. By doc, I got that i have write rule for every different url. Is it so? I just wanted a common routing rule which works for all urls something like

Route::get('/{Controller}/{method}', $Controller.'@'.$method);

I know this is wrong, I tried a lot but can't get proper sentence.

I simply want that first segment after Base Url become controller name and second segment become method name.

2

There are 2 best solutions below

0
On BEST ANSWER

For the time I used this,

$controller = '';
$method = '';
$segments = $_SERVER['REQUEST_URI'];
$segments = str_replace('/cp/public/index.php/', '', $segments);
$arr_seg = explode('/',$segments);
if(count($arr_seg) > 1){
    $controller = $arr_seg[0];
    $method = $arr_seg[1];
}

Route::get('/{var1}/{var2}',$controller.'@'.$method);

And it's working for me.

0
On

I suppouse You can - if You must - do sth like that:

Route::get('/{controller}/{method}', function($controller, $method) {
    $name = "\App\Http\Controllers\\" . $controller . 'Controller';
    $class = new $name();
    return $class->{$method}();
});

or if You have static methods:

Route::get('/{controller}/{method}', function($controller, $method) {
    return call_user_func(array("\App\Http\Controllers\\" . $controller . 'Controller', $method));
});

But I don't think this is a good idea.

This way You loose all 'power' of laravel routing (because this is just one route).

For example:

  • You can't refer to choosen method by route name
  • You can't attach middleware to specific routes etc.

It is always better to be more explicit.

At least You can use one of these:

  1. Route::resource() or
  2. Rotute::controller()

In both cases You will need to define routes for each controller, though.

Examples:

  1. Route::resource('photo', 'PhotoController');

and then follow method name convention in Your controller (index, create etc.).

More here: http://laravel.com/docs/5.0/controllers#restful-resource-controllers

  1. Route::controller('users', 'UserController');

and then prefix Your controller method by http method like: public function getIndex()

More here: http://laravel.com/docs/5.0/controllers#implicit-controllers