Regarding the use of named routes, these 2 lines allow me to access the same page so which is correct?
// Named route
Route::get('test/apples', array('as'=>'apples', 'uses'=>'TestController#getApples'));
// Much simpler
Route::get('apples', 'TestController#getApples');
Is there any reason I should be using named routes if the latter is shorter and less prone to errors?
Named routes are better, Why ?
It's always better to use a named route because insstsead of using the url you may use the name to refer the route, for example:
return Redirect::to('an/url');
Now above code will work but if you would use this:
return Redirect::route('routename');
Then it'll generate the url on the fly so, if you even change the url your code won't be broken. For example, check your route:
Route::get('apples', 'TestController#getApples');
Route::get('apples', array('as' => 'apples.show', 'uses' => 'TestController#getApples'));
Both routes are same but one without name so to use the route without name you have to depend on the url, for example:
return Redirect::to('apples');
But same thing you may do using the route name if your route contains a name, for example:
return Redirect::route('apples.show');
In this case, you may change the url from apples to somethingelse but still your Redirect will work without changing the code.
The only advantage is it is easier to link to, and you can change the URL without going through and changing all of its references. For example, with named routes you can do stuff like this:
URL::route('apples');
Redirect::route('apples');
Form::open(array('route' => 'apples'));
Then, if you update your route, all of your URLs will be updated:
// from
Route::get('test/apples', array('as'=>'apples', 'uses'=>'TestController#getApples'));
// to
Route::get('new/apples', array('as'=>'apples', 'uses'=>'TestController#getApples'));
Another benefit is logically creating a URL with a lot parameters. This allows you to be a lot more dynamic with your URL generation, so something like:
Route::get('search/{category}/{query}', array(
'as' => 'search',
'uses' => 'SearchController#find',
));
$parameters = array(
'category' => 'articles',
'query' => 'apples',
);
echo URL::route('search', $parameters);
// http://domain.com/search/articles/apples
The only reason to name the route is if you need to reference it later. IE: from your page in a view or something, check whether you are in that route.
Related
In route.php I defined a route to a controller with 2 tokens on it.
Route::get('/{category}/{slug}', 'projectController#detail');
Everything is working fine till when there is a call to a URL that have the same structure but has nothing to do with the one that has to be caught by that route shown below.
So when I have for example "/admin/tags", the controller below is triggered because it has the same structure of "/{category}/{slug}" and of course it gives me an error, because it doesn't find a variable.
So now I fixed the problem moving that route on the bottom, but I believe I have to do something to prevent this behavior in advance, cause if I have multiple routes with different tokens everything would be triggered every time and there would be a mess.
So, what is it supposed to do in these cases?
P.S. I'm super beginner with Laravel
use some constraint to the route, reference parameters-regular-expression-constraints. For example:
Route::get('user/{name}', function ($name) {
//
})
->where('name', '[A-Za-z]+');
Or you can make the most specific before unspecific one. For example, in this sequence:
Route::get("/admin/tags", '......');
Route::get('/{category}/{slug}', 'projectController#detail');
if route need two token like that, i'm usually add prefix so my routes looks like this
Route::get('/categories/{category}/slug/{slug}', 'ProjectController#detail');
or
Route::get('/categories/{category}/{slug}', 'ProjectController#detail');
I was having the same issue.
I have constraints on every path parameter (as you always should) and unfortunately the conflict occurs between the following:
Route::get('{userId}/{path}', [
'as' => 'products',
'uses' => 'HomeController#click'
])->where(['id' => '[0-9]+', 'path' => '[0-9a-fA-F]+']);
Route::get('link/{link_path}', [
'as' => 'product-link',
'uses' => 'UserController#productLink'
])->where(['link_path' => '[0-9a-fA-F]+']);
Where even though the one path has the prepended 'link/' in the path it still tried to hit the other. By placing the route with the prepended 'link/' above the other route it took priority and works.
Personally I think if you have a condition that isn't met on the route where clause it should skip the route and move on to the next. It doesn't really make sense to me to put a conditional that doesn't actually get passed up if the conditions aren't met.
Hopefully this helps anyone else having this issue.
My laravel application has a model - Video. It is the main model so the route was named videos. But after the development I discovered that there is a folder on the production server named videos
So now rewriting the url to include index.php in .htaccess does not work.
I cannot change the name of videos folder which is already present.
I cannot change the db table name either. I don't want to do that, its too much work.
Is there a way to change the route name to something else like lvideos or vvideos?
I tried changing it in routes but it seems there are other places where I have to change it. It throws me an error in the controller.
Can anyone suggest a solution for this?
I don't want to give the link with index.php to the users
Thank you.
You will have to change the route anywhere it is referenced.
In the future if you think a route might change, you could use named routes and then reference the route name anywhere you need to use it.
For example:
Route::group(['prefix' => 'videos'], function() {
Route::get('/', [
'uses' => 'VideosController#index',
'as' => 'videos.index',
]);
Route::get('{id}', [
'uses' => 'VideosController#show',
'as' => 'videos.show',
]);
});
Then everywhere you use these routes you use the name, for example in a view:
Videos
The link will still work even if you change the route to Route::group(['prefix => 'iVideos']); Even though the route changed, the name did not.
I have the following in my routes.php
Route::resource('g', 'GameController');
I link to these generated routes via HTML::linkRoute('g.index', 'Title', $slug) which produces a link to http://domain/g/demo-slug
What I am looking to do is verify if it is possible to have the prefix be declared in one place so I'm not hunting for links if a URL structure were to change.
For example, I would want to change http://domain/g/demo-slug to http://domain/video-games/demo-slug
I was hoping to use the similar functionality with the standard routes, but that does not seem to be available to resource routes.
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#getUpdated'));
Route::group() takes a 'prefix'. If you put the Route::resource() inside, that should work.
Tangent, I find this reads better:
Route::get('/', array('uses' => 'HomeController#getUpdated', 'as' => 'home'));
As far as I know it's true you can't have named routes for a resource controllers (sitation needed) but you can contain them in a common space using Route::group() with a prefix. You can even supply a namespace, meaning you can swap out an entire api with another quickly.
Route::group(array(
'prefix' => 'video-games',
'before' => 'auth|otherFilters',
'namespace' => '' // Namespace of all classes used in closure
), function() {
Route::resource('g', 'GameController');
});
Update
It looks like resource controllers are given names internally, which would make sense as they are referred to internally by names not urls. (php artisan routes and you'll see the names given to resource routes).
This would explain why you can't name or as it turns out is actually the case, rename resource routes.
I guess you're probably not looking for this but Route:group is your best bet to keep collections of resources together with a common shared prefix, however your urls will need to remain hard coded.
You can give custom names to resource routes using the following syntax
Resource::route('g', 'GameController', ['names' => [
'index' => 'games.index',
'create' => 'games.create',
...
]])
This means you can use {!! route('games.index') !!} in your views even if you decided to change the URL pattern to something else.
Documented here under Named resource routes
I'n new to Laravel and I'm not quite sure of all the routing stuff yet, so I want to do things the way I'm comfortable with for the time, which is accessing a controller method via url. So I have a controller called User, in that a function called getLogin(). I want to access this via 'mydomain.com/user/login'. It doesn't currently work, so how do I do this?
While I agree with Phil Sturgeon's article that for a typical app, it's wise to make routes as obvious as possible, there are some cases where a url segment to controller method scheme might be convenient. I sometimes use Laravel for prototyping/testing some code and need a predictable url-to-method to spin off examples. You can grab the segment using Request::segment() and camelcase it using Laravel's Str::camel(). For example, with a route like:
Route::get('/lara-learn/{method}',
array(
'as' => 'lara-learn_' . Request::segment(2),
'uses' => 'LaraLearnController#' . Str::camel( Request::segment(2) )
)
);
You can visit /lara-learn/lara-config and land on the laraConfig() method:
class LaraLearnController extends BaseController {
public function laraConfig(){
return "hey from laraConfig";
}
}
If we want, we can also choose the controller dynamically from the url, say using the first segment. So we can generalize our route even more:
Route::get('/{controller}/{method}',
array(
'as' => Request::segment(1) . '_' . Request::segment(2),
'uses' => studly_case( Request::segment(1) ) . 'Controller#' . Str::camel( Request::segment(2) )
)
);
Visiting /lara-learn/lara-config should land us on the laraConfig method example above.
Laravel does not automatically map routes in controller/method fashion.
You have not posted what is in your routes.php file, but one of the simplest approaches is to do this:
Route::get('users/login', array('as' => 'login', 'uses' => 'User#getLogin'));
There are multiple approaches, though. You might consider reading the docs about routing
Route::resource('/recipes', 'recipesController#index');
you have to make route like this and u have to access it in url as
localhost/projectname/public/recipes
My route setup :
Zend_Controller_Front::getInstance()
->getRouter()
->addRoute('view', new Zend_Controller_Router_Route('controller/action/:name'))
My link in view :
$this->url(array("name" => "John"), "view", TRUE);
// returns "controller/action/John" as should
Now, when I am at controller/action/John, how do I get the name from URL ? I tried
$this->getRequest()->getParam("name");
but the name param isn't there - getRequest() returns only controller, action and module params.
When you set up your route configuration the route definition should either directly match the controller/action names or be set with defaults. Actually setting the defaults in any case is just good practice and helps you avoid issues like this.
So, in your case according to the comments your route should probably look like this.
$defaults = array(
'controller'=> 'offers',
'action' => 'view',
'name' => ''
);
$route = new Zend_Controller_Router_Route('offers/view/:name',$defaults);
As mentioned in the comments you can always check what route has been used with Zend_Controller_Front::getInstance()->getRouter()->getCurrentRouteName(). If it doesn't show your expected route the Router isn't able to find a match and moves on until it usually ends in the "default" route.
As a side note to your question: When you use $this->url(array("name" => "John"), "view", TRUE) you only create the link based on the route. This method is only part of the view and does nothing in terms of dispatching to a controller or action.
For those who found this question and for future reference, you can get params from route using this : $this->params()->fromRoute('param1', 0); in Zend Framework 2 at least. This is what I was looking for in this question.