i have multiple namespaces in my application namely FrontEnd namespace and BackEnd namespace, now in my routes file i would like to know the correct way to direct each route to a namespace.
This is what i have at the moment:
Route::group(['namespace' => 'FrontEnd'], function()
{
Route::group(array('prefix' => '/api/v1/'), function()
{
});
});
Now the above works alright (at least when i tried it) but just to make sure i was doing the right thing i wanted to ask so i don't experience and problems in the future.
I would like to know if this is the correct way of going about it instead:
Route::group(array('prefix' => '/api/v1/'), function()
{
Route::group(['namespace' => 'FrontEnd'], function()
{
});
});
Or does it not matter at all whichever way i decide to go?
you can pass all your option for route group in attribute array like this
Route::group(array('middleware' => 'youemiddleware', 'prefix' => 'yourprefixes', 'namespace' => 'yournamespaces', 'domain' => 'subdomains'), function()
{
// your routes
});
I see no preference one over the other.
How about this?
Route::group(array('prefix' => '/api/v1/', 'namespace' => 'FrontEnd'), function()
{
// code goes here
});
Related
I'm creating an API that is available only via POST. I'm planning to have more than one version of the API, so the current one uses v1 as part of the URL.
Now, in case an API call is made via GET, PUT or DELETE I would like to return a Fail response. For this I'm using Route::match(), which works perfectly fine in the code below:
Route::group(['namespace'=>'API', 'prefix' => 'api/v1', 'middleware' => 'api.v1'], function() {
Route::match(['get', 'put', 'delete'], '*', function () {
return Response::json(array(
'status' => 'Fail',
'message' => 'Wrong HTTP verb used for the API call. Please use POST.'
));
});
// User
Route::post('user/create', array('uses' => 'APIv1#createUser'));
Route::post('user/read', array('uses' => 'APIv1#readUser'));
// other calls
// University
Route::post('university/create', array('uses' => 'APIv1#createUniversity'));
Route::post('university/read', array('uses' => 'APIv1#readUniversity'));
// other calls...
});
However, I noticed that I could group the routes even more, to separate the API version and calls to specific entities, like user and university:
Route::group(['namespace'=>'API', 'prefix' => 'api'], function() {
Route::match(['get', 'put', 'delete'], '*', function () {
return Response::json(array(
'status' => 'Fail',
'message' => 'Wrong HTTP verb used for the API call. Please use POST.'
));
});
/**
* v.1
*/
Route::group(['prefix' => 'v1', 'middleware' => 'api.v1'], function() {
// User
Route::group(['prefix' => 'user'], function() {
Route::post('create', array('uses' => 'APIv1#createUser'));
Route::post('read', array('uses' => 'APIv1#readUser'));
});
// University
Route::group(['prefix' => 'university'], function() {
Route::post('create', array('uses' => 'APIv1#createUniversity'));
Route::post('read/synonym', array('uses' => 'APIv1#readUniversity'));
});
});
});
The Route::match() in the code above does not work. When I try to access any API call with e.g. GET, the matching is ignored and I get MethodNotAllowedHttpException.
Can I get the second routes structure to work with Route::match() again? I tried to put it literally everywhere in the groups already. Putting the Route::match() outside of the hole structure and setting path to 'api/v1/*' does dot work either.
If you use the post() function you don't need to deny manualy other verb.
What you can do is to create a listener for the MethodNotAllowedHttpException and display what you want. Or you can also use any() function at the end of your route's group to handle all route that is not defined.
I am working on a platform that allows users to run their own site in either a sub folder of the main website domain, or map a custom domain for their site.
When using a custom domain the URL structure for each route is slightly different in that it is prefixed with the username, but when using a custom domain then this prefix is not used.
Is there a clever way to achieve this in my Route::group to handle both request types in one route and successfully use reverse routing to produce the appropriate URL based on the parameters passed to it.
Below is an example of using the prefix
Route::group(array( 'prefix' => 'sites/{username}'), function() {
Route::get('/photos/{album_id}.html', array('uses' => 'Media\PhotosController#album_view', 'as' => 'photo_album'));
});
And here is an example of using a custom domain
Route::group(array('domain' => '{users_domain}'), function() {
Route::get('/photos/{album_id}.html', array('uses' => 'Media\PhotosController#album_view', 'as' => 'photo_album'));
});
Ideally I would like to be in a position where I could use either
route('photo_album', ['username' => 'johnboy', 'album_id' => 123] )
and be returned
http://www.mainwebsitedomain.com/sites/johnboy/photos/123.html
or call the same route with different parameters
route('photo_album', ['users_domain' => 'www.johnboy.com', 'album_id' => 123] )
and be returned
http://www.johnboy.com/photos/123.html
This is a pretty tricky question so expect a few not so perfect workarounds in my answer...
I recommend you read everything first and try it out afterwards. This answer includes several simplification steps but I wrote down whole process to help with understanding
The first problem here is that you can't have multiple routes with the same name if you want to call them by name.
Let's fix that by adding a "route name prefix":
Route::group(array( 'prefix' => 'sites/{username}'), function() {
Route::get('/photos/{album_id}.html', array('uses' => 'Media\PhotosController#album_view',
'as' => 'photo_album'));
});
Route::group(array('domain' => '{users_domain}'), function() {
Route::get('/photos/{album_id}.html', array('uses' => 'Media\PhotosController#album_view',
'as' => 'domain.photo_album'));
});
So now we can use this to generate urls:
route('photo_album', ['username' => 'johnboy', 'album_id' => 123] )
route('domain.photo_album', ['users_domain' => 'www.johnboy.com', 'album_id' => 123])
(No worries we will get rid of domain. in the URL generation later...)
The next problem is that Laravel doesn't allow a full wildcard domain like 'domain' => '{users_domain}'. It works fine for generating URLs but if you try to actually access it you get a 404. What's the solution for this you ask? You have to create an additional group that listens to the domain you're currently on. But only if it isn't the root domain of your site.
For simplicity reasons let's first add the application domain to your config. I suggest this in config/app.php:
'domain' => env('APP_DOMAIN', 'www.mainwebsitedomain.com')
This way it is also configurable via the environment file for development.
After that we can add this conditional route group:
$currentDomain = Request::server('HTTP_HOST');
if($currentDomain != config('app.domain')){
Route::group(array('domain' => $currentDomain), function() {
Route::get('/photos/{album_id}.html', array('uses' => 'Media\PhotosController#album_view',
'as' => 'current_domain.photo_album'));
});
}
Soooo... we got our routes. However this is pretty messy, even with just one single route. To reduce the code duplication your can move the actual routes to one (or more) external files. Like this:
app/Http/routes/photos.php:
if(!empty($routeNamePrefix)){
$routeNamePrefix = $routeNamePrefix . '.';
}
else {
$routeNamePrefix = '';
}
Route::get('/photos/{album_id}.html', ['uses' => 'Media\PhotosController#album_view',
'as' => $routeNamePrefix.'photo_album']);
And then the new routes.php:
// routes for application domain routes
Route::group(['domain' => config('app.domain'), 'prefix' => 'sites/{username}'], function($group){
include __DIR__.'/routes/photos.php';
});
// routes to LISTEN to custom domain requests
$currentDomain = Request::server('HTTP_HOST');
if($currentDomain != config('app.domain')){
Route::group(['domain' => $currentDomain], function(){
$routeNamePrefix = 'current_domain';
include __DIR__.'/routes/photos.php';
});
}
// routes to GENERATE custom domain URLs
Route::group(['domain' => '{users_domain}'], function(){
$routeNamePrefix = 'domain';
include __DIR__.'/routes/photos.php';
});
Now the only thing missing is a custom URL generation function. Unfortunately Laravel's route() won't be able to handle this logic so you have to override it. Create a file with custom helper functions, for example app/helpers.php and require it in bootstrap/autoload.php before vendor/autoload.php is loaded:
require __DIR__.'/../app/helpers.php';
require __DIR__.'/../vendor/autoload.php';
Then add this function to the helpers.php:
function route($name, $parameters = array(), $absolute = true, $route = null){
$currentDomain = Request::server('HTTP_HOST');
$usersDomain = array_get($parameters, 'users_domain');
if($usersDomain){
if($currentDomain == $usersDomain){
$name = 'current_domain.'.$name;
array_forget($parameters, 'users_domain');
}
else {
$name = 'domain.'.$name;
}
}
return app('url')->route($name, $parameters, $absolute, $route);
}
You can call this function exactly like you asked for and it will behave like the normal route() in terms of options and passing parameters.
I started working with Laravel last week and I'm facing a minor problem with routes.
when i do the following:
Route::group(array('before' => 'auth'), function() {
Route::resource('admin', 'VacatureController');
Route::get('admin/test', array('uses' => 'VacatureController#create'));
Route::post('admin/test', array('uses' => 'VacatureController#store'));
});
and i go to admin/test, i get an empty page.
when i change admin/test to something like test/test like:
Route::group(array('before' => 'auth'), function() {
Route::resource('admin', 'VacatureController');
Route::get('test/test', array('uses' => 'VacatureController#create'));
Route::post('test/test', array('uses' => 'VacatureController#store'));
});
it works fine. I looked itup in the documentation, but i didn't become anything wiser.
Can someone please enlighten me?
Try putting the Route::resource as the last route. Laravel will try all routes in the order you put them in the route file, so when you put the resource route first only this one will be checked because it expects all admin routes to be there.
Route::group(array('before' => 'auth'), function() {
Route::get('admin/test', array('uses' => 'VacatureController#create'));
Route::post('admin/test', array('uses' => 'VacatureController#store'));
Route::resource('admin', 'VacatureController');
});
I've two route controllers within a route group:
Route::group(array('before' => 'auth'), function()
{
Route::controller('dashboard/', 'DashboardController');
Route::controller('dashboard/profile', 'DashboardProfileController');
});
That works until I add prefix key to the array:
Route::group(array('prefix' => 'dashboard', 'before' => 'auth'), function()
{
Route::controller('/', 'DashboardController');
Route::controller('/profile', 'DashboardProfileController');
});
It's weird as the first route controller works since I can access localhost/dashboard but the second fails on localhost/dashboard/profile and or localhost/dashboard/profile/edit
What's wrong here?!
It seems both of them route to one location, therefore the longest one should go first because it is interpreted as argument.
Route::group(array('prefix' => 'dashboard', 'before' => 'auth'), function()
{
Route::controller('/profile', 'DashboardProfileController');
Route::controller('/', 'DashboardController');
});
Simple little question :
on Laravel 4, it seems that a group of routes into an another group isn't working.
Is there any solution to make it work ? Or do I have to write my routes in another way ?
Example :
Route::group(array('prefix' => 'app', 'before' => 'auth_api'), function()
{
Route::group(array('prefix' => '{app_id}'), function()
{
Route::get('/', 'AppController#show');
Route::group(array('prefix' => 'achievement'), function()
{
Route::get('/{id}', 'AchievementController#show');
});
});
});
I'm unable to get a route to (example here) app/1234/achievement/1
Maybe it's too complex here. I have not any error, just a blank page (no PHP error)
Laravel 4 isn't offering this possibility but this package : https://github.com/jasonlewis/enhanced-router do the work.