Brightside
Brightside

Reputation: 131

laravel 4 - multiple routes to the same controller

I am trying to avoid this code:

Route::get('/', array('as' => 'create_content', 'uses' => 'SameController@create'));
Route::get('create_content', array('as' => 'create_content', 'uses' => 'SameController@create'));

and combined them into one route. because the controller is the same.

so this controller will be active when u go to the index "/" and to "create_content".

And if i am already here - maybe someone can elaborate for me about the purpose of "as" in the array?

Thanks!

Upvotes: 1

Views: 4299

Answers (2)

Acorn1010
Acorn1010

Reputation: 124

In Laravel you're not restricted to static values for your paths. You can also use {}'s to denote a variable. Adding a ? after the variable name makes that variable optional. These variables are passed to your routing method (in this case, the "create" method of SameController).

This can be combined with the where method to pull off what you want. The where method allows you to define RegEx restrictions on what's allowed by a variable.

Another alternative is to use a Route::pattern, which is basically a more "global" version of where(). I've included an example of both for your convenience. :)

As for 'as', you're able to name a route in Laravel. After naming a route with 'as', you can access it through some of Laravel's useful functions, such as URL::route('nameOfRoute') or Redirect::route('nameOfRoute');

A functioning example is below:

Route::pattern('myPattern', '(create_content)?');

Route::get('/{path?}', array('as' => 'nameOfRoute', 'uses' => 'SameController@create')
)->where('path', '(create_content)?');

// This is functionally equivalent to the above Route::get.
// Route::get('/{myPattern?}', array('as' => 'nameOfRoute', 'uses' => 'SameController@create')
// );

// Example of how to make use of the 'as' defined above.
Route::get('create_more_content', function() {
    return Redirect::route('nameOfRoute');
});

Upvotes: 3

Bielco
Bielco

Reputation: 275

Despite you cannot avoid that code, because of the following reason. As it is the same route to the same controller, the request is still different.

So i think you have two options...

1) Go with the above code

or

2) hack your .htaccess file and redirect it to / when the request is create_content

And believe me, the first is the most easiest way.

The question you need to ask is, do i need that second route. Is there content spreaded like url's that point to that location ? If not that much i would drop the second entirely.

Upvotes: 0

Related Questions