0

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.

Laurence
  • 58,936
  • 21
  • 171
  • 212
Aniket Singh
  • 2,464
  • 1
  • 21
  • 32
  • possible duplicate of [Laravel 4 : Route to localhost/controller/action](http://stackoverflow.com/questions/18178023/laravel-4-route-to-localhost-controller-action) – Pᴇʜ Jun 17 '15 at 07:48
  • 1
    this is a bad pactice – Emeka Mbah Jun 17 '15 at 07:48
  • I recommend not to do this! See https://philsturgeon.uk/blog/2013/07/beware-the-route-to-evil/ to read about the benefits of defining routes – Pᴇʜ Jun 17 '15 at 07:50

2 Answers2

2

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

D. Cichowski
  • 777
  • 2
  • 7
  • 24
-1

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.

Aniket Singh
  • 2,464
  • 1
  • 21
  • 32