Laravel - can I control routes by rule?

284 views Asked by At

So I have a Laravel Controller (MainController.php) with the following lines:

...
public function _settings_a(){
    return view('_settings_a');
}
public function _settings_b(){
    return view('_settings_b');
}
public function _settings_c(){
    return view('_settings_c');
}
public function _settings_d(){
    return view('_settings_d');
}
public function _staff_a(){
    return view('_staff_a');
}
public function _staff_b(){
    return view('_staff_b');
}
public function _staff_c(){
    return view('_staff_c');
}
...

And my routes.php is as follows:

Route::any('_staff_a''MainController@_staff_a');
Route::any('_staff_b''MainController@_staff_b');
...
etc.

It seems there are a LOT of lines and a LOT of things to change if I change my mind...

I was wondering if I can have some regex in routes.php and an equivalent regex in MainController.php for handling routes that begin with an underscore (_)?

Can any Laravel experts share some tips/suggestions? I'm quite new to the framework.

2

There are 2 answers

0
Joel Hinz On BEST ANSWER

Sure - just add it as a parameter. E.g. like this:

Route::any('_staff_{version}', 'MainController@_staff');

public function _staff($version) {
    return view('_staff_'.$version);
}
0
A3mercury On

I don't think you need to mess with regex. You can use implicit controllers Route::controller() which isn't the BEST solution, but will do what I think you are wanting.

So instead of

Route::any(..)

you can do

Route::controller('url', 'MainController');

So your route to whatever 'url' is will send you to this controller. Follow that with a '/' and then add whichever method in the controller you want to call.

Here is an example:

My url: 'http://www.example.com/users'

// routes.php
Route::controller('users', UserController');

// UserController.php
public function getIndex()
{
  // index stuff
}

Now I send a request like: http://www.example.com/users/edit-user/125

// UserController.php
public function getEditUser($user_id)
{
  // getEditUser, postEditUser, anyEditUser can be called on /users/edit-user
  // and 125 is the parameter pasted to it
}

Doing it this way should allow you to be able to just send a request (post or get) to a url and the controller should be able to call the correct method depending on the url.

Here are some more rules about it: http://laravel.com/docs/5.1/controllers#implicit-controllers