Ad

Intelligent Routing With Controller

There is a way automatically set routes using my controller's methods?

Example: I have a PagesController with 'home' or 'index', 'about' and 'contact' methods. Can I set routes for every method without explictly typing them?

Something like

Route::?('PagesController');

or

Route::get('/{page}', '[email protected]{page}');

?

yeah, i'm new in laravel...

Ad

Answer

No, it's not possible. Assuming you use standard RESTful methods like index, create, edit, store, update and destroy then yes, you can just write:

Route::resource('cars', 'CarController');

and you will have created routes for list of cars, route for edit, create and so on

This is explained in Resource Controller documentation part.

But remember you can always create routes that will "catch" all other urls, for example you could create route like this:

Route::get('{page?}', '[email protected]')->where('page', '.+')

And this route should be defined as last one from all other routes.

And now you can define handle method in this controller like this:

public function handle($page = 'home') 
{
    // here you can put any logic you want, for example:

   if (method_exists($this, $page)) {
       return $this->$page();
   }

   abort(404);
}

and now you can define methods that match your urls for example:

public function home()
{
   // return some response here
}

public function index()
{
  // return some response here
}

This way you should be able to achieve what you want without need of manually defining multiple routes in your routing file.

Ad
source: stackoverflow.com
Ad