I am working on laravel project to learn the framework, i have a question comes in my mind about routing.
Is the router a singleton class? because i try the following in the route.php file
$route1 = App::make('router');
$route2 = App::make('router');
$route3 = App::make('router');
$route4 = App::make('router');
$route1->get('/r1', function(){
echo "route 1";
});
$route2->get('/r2', function(){
echo "route 2";
});
$route3->get('/r3', function(){
echo "route 3";
});
$route3->get('/r4', function(){
echo "route 4";
});
var_dump($route1->getRoutes());
as you see i have create four objects of router class, each object add one route. last line prints the routes for $route1 object, and the output is.
object(Illuminate\Routing\RouteCollection)[112]
protected 'routes' =>
array (size=2)
'GET' =>
array (size=4)
'r1' =>
object(Illuminate\Routing\Route)[120]
...
'r2' =>
object(Illuminate\Routing\Route)[122]
...
'r3' =>
object(Illuminate\Routing\Route)[124]
...
'r4' =>
object(Illuminate\Routing\Route)[126]
...
The output shows that the $route1 object have the other routes created by $route2, $route3, and $route4 objects.
How the routs shared between them?
You have two components here a route and a route collection. When you register a route they all get added to a route collection. The best to show you is by seeing the symfony route components. http://symfony.com/doc/current/components/routing/introduction.html
You have a route, route collection, request, and url matcher.
You create routes and gather them in a route collection.
The get the request url and use the matcher to match the url with the route.
Related
I have already
a/{id}
api
Now I want
a/b
But it is not hitting a/b, it is hitting a/{id} and taking b as {id}
How can I create a/b assuming I am not allowed to change a/{id}?
Framework Laravel.
$apiRoutes = [
// Dev routes
'get_a_by_id' => ['get', 'a/{id}','AController#getA'],
// App routes
'fetch_all_b' => ['get','a/b', 'BController#getB'],
]
This is my code route.php
Even reordering also doesn't work.
What you can do is
First place a/b above a/{id} and add ->where(['id' => '[0-9]+'); this will make sure that the route a/{id} will trigger only if there is numeric value.
You can change regex based on your needs.
Route::get('a/b', function () {
//code
});
Route::get('a/{id}', function ($id) {
//code
})->where(['id' => '[0-9]+');
It depends in which order you define them, you need to first create the specific route a/b then below the wildcard one.
Route::get('a/b', function () {
dd('testing b');
});
Route::get('a/{id}', function ($id) {
dd('testing', $id);
});
The short answer is to define a/b before a/{id}
Here's my example:
Route::get('/v1/smsportal/search/{type?}/{search?}', 'SMSPortals#search');
Route::get('/v1/smsportal/{id?}', 'SMSPortals#get');
Route::post('/v1/smsportal', 'SMSPortals#save');
Route::post('/v1/smsportal/{id?}', 'SMSPortals#update');
Route::delete('/v1/smsportal/{id?}', 'SMSPortals#delete');
/v1/smsportal/search will be called before /v1/smspotal/{id} if I call for search.
I am working on a legacy code, a project built with Laravel 5.2, and I am getting an error:
Route pattern "/api/v0/taxonomy/{term}/{{term}}" cannot reference variable name "term" more than once.
For this route:
/post/106
This is are my routes:
Route::group(['prefix' => 'api'], function() {
Route::group(['prefix' => 'v0'], function () {
Route::get('route/{a?}/{b?}/{c?}/{d?}', 'DynamicRouteController#resolve');
Route::get('id/{id}', 'DynamicRouteController#resolveId');
Route::get('search', 'SearchController#search');
Route::resource('taxonomy/{term}','TaxonomyController');
});
});
Not sure, why am I getting this error?
When you define a route as a resource then Laravel seems to create all the routes necessary for your resource: GET, POST, PATCH, DELETE.
So you would just need to define Route::resource('taxonomy','TaxonomyController'); or Route::resource('taxonomy.post','TaxonomyPostController');
Check docs
You just need rename your route parameter like this:
Route::resource('taxonomy/{term}','TaxonomyController', ['parameters'
=> ['{term}' => 'your_name']]);
be careful!!!!. you need insert bracket. this will cause wrong result:
Route::resource('taxonomy/{term}','TaxonomyController', ['parameters'
=> ['term' => 'your_name']] );
attention:
'your_name' should not be same as your parameter so this method make wrong
result.
Route::resource('taxonomy/{term}','TaxonomyController', ['parameters'
=> ['{term}' => 'term']});
I am creating some hard coded routes that will likely be changed again freely in the future. To abstract the ideas a bit:
We have a controller/method BuySubscriptionController#start:
class BuySubscriptionController
function start()
{
$plan = Plan::findBySlug($request->get('plan'));
return view('someView', ['plan' => $plan]);
}
}
We currently have the following route:
Route::get('/buy-subscription/start', 'BuySubscriptionController#start');
This means the sales team would need to advertise the following urls:
site.com/buy-subscription/start?plan=plan-one
site.com/buy-subscription/start?plan=plan-two
Now we have been requested to have a few specialized routes:
site.com/purchase/the-basic-plan (plan-one)
site.com/purchase/the-mega-plan (plan-two)
Now I am trying to add these specialized urls to my routes. I was hoping to do something as follows, but does not work:
Route::get('/purchase/the-basic-plan', [
'uses' => 'BuySubscriptionController#start',
'with' => ['plan' => 'plan-one']
]);
Route::get('/purchase/the-mega-plan', [
'uses' => 'BuySubscriptionController#start',
'with' => ['plan' => 'plan-two']
]);
Is there any way to achieve this, simply, without over engineering some new translation layer? Keep in mind that next week the url might be /buy/the-god-plan meaning plan-one, so being able to simple add a line to my routes seems ideal.
You can define a route that takes the plan as a parameter, and use Regular Expression Constraints so that parameter can only take certain values that you allow. So your route definition can look like this:
Route::get('/purchase/{plan}', 'BuySubscriptionController#start')
->name('purchase-plan')
->where('plan', 'the-basic-plan|the-mega-plan');
Then in your controller action just use the parameter:
class BuySubscriptionController
{
protected $plans = [
'the-basic-plan' => 'plan-one',
'the-mega-plan' => 'plan-two'
];
function start($plan)
{
// You can use an associative array to convert the $plan parameter
// into the value you need for querying the database
$plan = Plan::findBySlug($this->plans[$plan]);
return view('someView', ['plan' => $plan]);
}
}
If you need to generate URLs for the route you can just use the route helper method and pass it the plan name:
route('purchase-plan', 'the-basic-plan');
And you'll get:
site.com/purchase/the-basic-plan
This solution allows you to add any number of plan names by just adding the public plan for the URL in the where constraint of the route, then associating that value with the one you need for the query in your controller's $plans property.
In my routes.php I have the following group:
Route::group(array('before' => 'checkSomething', 'prefix' => '{lang}'), function() {
echo "1";
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#home'));
});
And the filter attached to it:
Route::filter('checkSomething', function(){
echo "2";
if(!somethingNotRight($something)){
return Redirect::route('index', array()));
}
});
My question is, why is the route inside the route group getting called first, and after that the filter? If I execute this code, I get the following result:
21
But what I want is:
12
Pretty simple isn't it? You are aplying your filter BEFORE the app hits the controller of the route, if you want to apply filter after just change:
Route::group(array('after' => 'checkSomething', 'prefix' => '{lang}')
The code inside the Route::group closure isn't called at the moment the route is executed. It's called very early to register all the routes. The filter is working correctly, but to test that you'd need to put the echo inside the controller
I have this defined in my routes.php file
Route::post('gestionAdministrador', array('as' => 'Loguearse', 'uses' => 'AdministradorController#Login'));
Route::post('gestionAdministrador', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController#RegistrarAdministrador'));
And in my login.blade.php file, the form starts as this
{{ Form::open(array('route'=>'Loguearse'))}}
I dont know why when i submit the form takes the second route instead the first one, even though I am pointing to the first one.
There must be a way to go to the same url from two different forms, that is what I want.
If you have two routes with the exact same URI and same method:
Route::post('gestionAdministrador', array('as' => 'Loguearse', 'uses' => 'AdministradorController#Login'));
Route::post('gestionAdministrador', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController#RegistrarAdministrador'));
How can Laravel know the difference between them when something hit /gestionAdministrador?
It will always assume the first one.
The name you set 'as' => 'RegistrarAdministrador' will be used to create URLs based on that route name, only, when something (browser, curl...) hit the URL the only ways to differentiate them is by
1) URL
2) URL parameters (which is basically number 1 plus parameters)
3) Method (GET, POST)
So you could change them to something like:
Route::post('gestionAdministrador/loguearse', array('as' => 'Loguearse', 'uses' => 'AdministradorController#Login'));
Route::post('gestionAdministrador/registrar', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController#RegistrarAdministrador'));
EDIT 2
What you really need to understand is that the name you give to a route ('as' => 'name') will not be part of your url, so this is not something that Laravel can use to differentiate your two URls, this is for internal use only, to identify your routes during the creation of URLs. So, those instructions:
$loguearse = URL::route('Loguearse');
$registrar = URL::route('RegistrarAdministrador');
Would generate exactly the same URL:
http://yourserver.dev/gestionAdministrador
EDIT 1 - TO ANSWER A COMMENT
Redirecting in Laravel is easy, in your controller, after processing your form, in any of your methods you can just:
return Redirect::to('/');
or
return Redirect::route('home');
Having a route like this one:
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#index'));
So, your controller would look like this:
class AdministradorController extends Controller {
public function RegistrarAdministrador()
{
...
return Redirect::route('home');
}
public function Login()
{
...
return Redirect::route('home');
}
}
Actually you have only one route in your route collection, because:
You have following routes declared:
Route::post('gestionAdministrador', array('as' => 'Loguearse', 'uses' => 'AdministradorController#Login'));
Route::post('gestionAdministrador', array('as' => 'RegistrarAdministrador', 'uses' => 'AdministradorController#RegistrarAdministrador'));
Both of these used post method and this is post method:
public function post($uri, $action)
{
return $this->addRoute('POST', $uri, $action);
}
It calls addRoute and here it is:
protected function addRoute($methods, $uri, $action)
{
return $this->routes->add($this->createRoute($methods, $uri, $action));
}
Here $this->routes->add means Illuminate\Routing\RouteCollection::add() and the add() method calls addToCollections() and it is as follows:
protected function addToCollections($route)
{
foreach ($route->methods() as $method)
{
$this->routes[$method][$route->domain().$route->getUri()] = $route;
}
$this->allRoutes[$method.$route->domain().$route->getUri()] = $route;
}
The $routes is an array (protected $routes = array();) and it's obvious that routes are grouped by methods (GET/POST etc) and in each method only one unique URL could be available because it's something like this:
$routes['post']['someUrl'] = 'a route';
$routes['post']['someUrl'] = 'a route';
So, in your case, the last one is replacing the first one and in this case you may use different methods to declare two routes using same URL so it would be in different array, something like this:
$routes['post']['someUrl'] = 'a route';
$routes['put']['someUrl'] = 'a route'; // Route::put(...)
There must be a way to go to the same url from two different forms
Yes, there is a way and it's simply that you have to use the same route as the action of your form and therefore, you don't need to declare it twice.
What you want to do is a bad idea, you shouldn't be logging in and registering from the same route. With that said what you are saying isn't really possible. Routing in Laravel is first come first served. Basically it checks the route until the URI matches one and then calls that method on the controller or executes the callback. Your routes have to be the other way in your routes file. This will be fixed by changing the url.