Location Code in Url - Laravel - laravel

I'm creating a directory for multiple locations for example, USA, UK and Canada.
I want something like this www.example.com/US and www.example.com/UK, www.example.com/CA
When someone visits www.example.com/US i want to list all listings under USA location. Similarly for other locations. For this i have a single database and multiple laravel installation for each country. (I'm new to laravel so do not know how to do this. I'm trying something on my own with my knowledge.)
I have added a prefix to the routes so that it adds the country code in the URL
Route::group(['prefix' => 'USA'], function(){
Route::get('/', 'Frontend\PagesController#index')->name('welcome');
});
When i visit www.example.com it shows page not found. However when i visit www.example.com/USA it works all fine.
I have two questions here.
1. Is this the right way to do it? Or are there any other methods with single installation like locales are handled.
2. How to use the default url as www.example.com/country-code-of-user (Auto Detect). I made a dropdown to change the country.
The first question is a general question which i wanted to check here with senior programmers. The later question is about the error im receiving "Page Not Found" which i want to solve.
Any help would be appreciated. Thanks

If you have you got user country then you can redirect user to the proper url using some code like as :
Route::get('/', function () {
return redirect('/USA');
});
// OR you can use any controller method to get conditional country redirection
Route::get('/', 'User#redirectTo')
//...with method
public redirectTo()
{
// if some condition
return redirect('/USA');
// else redirect to CA, UK and so on..
}

Related

Laravel: Creating route resource for sub directory

I am new to laravel and creating a spare parts maintenance app.
I created a route resource for spare parts using :
Route::resource('/parts' , 'SparePartsController');
This works fine.
Later I wanted to also create another route resource for spare parts categories. So I created the controller and used:
Route::resource('/parts/categories' , 'SpCategoriesController');
But this second resource wont work. When i go to www.myapp.com/parts/categories , I get a blank page. Any idea whats wrong?
Try to group the routes with a prefix for example:
Route::group(['prefix' => 'parts'], function(){
Route::get('/', 'SparePartsController');
Route::get('/categories', 'SpCategoriesController');
});
This will route all traffic from /parts to the SparePartsController and /parts/categories will call the SpCategoriesController
Look at the documentation for more information:
https://laravel.com/docs/5.3/routing#route-groups
If you want to call a specific function of the Controller just write:
Route::get('/', 'SparePartsController#functionName')
The SpCategoriesController resource route won't work because SparePartsController resource route is taking precedence over it.
To fix that, place your routes in this order:
Route::resource('/parts/categories' , 'SpCategoriesController');
Route::resource('/parts' , 'SparePartsController')
Ref: https://laravel.com/docs/5.3/controllers#restful-supplementing-resource-controllers

Allow CRUD only to Auth::user that owns the ressource

I currently work on a project where the User creates Models, that only he/she is allowed to see, edit or delete.
The Create Part done by Eloquent Relationships, but for the other operations I would like to combine it with Route Model binding and not manually in the controller. I tried solving it with middlewares, but I couldn't access the Ressource.
Can somebody point me to the right Direction, any best Practices are welcome!
Personally I use route model binding, but only allow the model to bind if the user owns the record.
This means that no matter what - people can never access someone elses record. So for example, in my route I can do
$router->get('property/{property}, ['uses' => PropertyController#show]);
Then in my RouteServiceProvider:
$router->bind('property', function($value) {
$property = \App\Property::findOrFail($value);
if ((int)$property->user_id !== (int)auth()->id()) {
abort (404);
}
return $property;
});
So in the example above - we have a property route, and it will try and find the property record given. It will then check that the user owns the record, otherwise it throws a 404 (but you could just redirect or something - up to you).

Laravel routing group for muliple domains with wildcards, how to handle domain suffixes?

I have 3 domains which, on my local server, take the format:
mydomainfirst.local
mydomainsecond.local
mydomainthird.local
In my routes.php file, I have the following:
Route::group(array('domain' => '{domain}.{suffix}'), function() {
Route::get('/', 'Primary#initialize');
});
The idea is to take the $domain variable in my controller and extract the first/second/third part from it, which works fine. However, now my site is online, this routing file no longer works and throws a Http-not-found exception. After a while, I have figured that the problem is that the domains have now taken the format mydomainfirst.co.uk. Because there are now 2 parts to the domain suffix, it seems I need to do this:
Route::group(array('domain' => '{domain}.{a}.{b}'), function() {
Route::get('/', 'Primary#initialize');
});
To get it to work. Which is stupid. How can I tell it to just accept any suffix? Is there an 'anything' wildcard I can use?
I have tried a few things like this answer but it doesn't work with route groups.
EDIT: It seems the Enhanced Router package would at least enable me to add a where clause to the route group, but does it solve the problem of how to set a wildcard that will match an indeterminate number of segments? I need something like:
{domain}.{anything}
That will match both:
mydomainfirst.local AND mydomainfirst.co.uk
?
Ok let me first say that the code of this package actually looks good and should work. Even if you can't get it running by installing you could take the files and use the code with your own service provider etc.
But there's also a kind of quick and dirty solution. (Actually the package does it pretty similar, but it looks a lot nicer ;))
First, here's how you can do it for one route:
Route::group(array('domain' => '{domain}.{tld}'), function(){
Route::get('/', 'Primary#initialize')->where('tld', '.*');
});
So the where condition for the route group actually gets set on the individual route.
Of course you don't want to do this for every route inside that group so you can use a simple foreach loop:
Route::group(array('domain' => '{domain}.{tld}'), function($group){
Route::get('/', 'Primary#initialize');
foreach($group->getRoutes() as $route){
$route->where('tld', '.*');
}
});
Note: The loop needs to come after all routes. Otherwise they won't registered and therefore not returned with getRoutes()

Laravel 4 multilanguage routing

I'm trying to implement a multilanguage routing.
The problem I'm facing lies in pointing out a route translated to more than one language, to a controller of its own. Let me give a simple example:
Let's say I have a simple route as follows
Route::get('/contacts', 'PageController#contacts');
And I want the same controller to be used for another route, but this time translated in another language, german for example.
Route::get('/kontakte', 'PageController#contacts');
For a simple webiste, with no more than 5-6 pages, writing down the routes for all languages would not be such a pain, but for more complex website, with huge amount of pages and having more than 2 available languages, a solution like this would be ugly.
I found an older topic here, where the author suggested loading a route.php file depending on the currently selected language. But still, this would require more than one file to be edited for further need.
A point of suggestion or currently working solution would be really appreciated.Thanks for your help.
Just some quick thoughts:
A solution can be to do grouping routes with a prefix like '/en/' and '/de/'.
So you will have /en/contact and /de/contact.
docs for this: http://laravel.com/docs/routing#route-prefixing
This way you can just create a loop through your available languages, and register the route.
The con here that you can't have a /de/kontake or /kontakte url, because there is 1 loop with routes, and they probably will be in English.
<?php
$languages = array('en', 'de');
foreach($langauges as $language)
{
Route::group(array('prefix' => $language), function()
{
Route::get('/', 'HomeController#index');
Route::get('contact', 'HomeController#contact');
});
}
A second solution will be to store all your routes in a database (or just an array to test it in the beginning)
You will need some Page and PageLocal models for it.
Page: id, name, controller
example: 1, contact, PageController#contact
PageLocal: id, page_id, language, slug
example: 1, 1, en, contact
example: 1, 1, de, kontakte
Loop through all Pages, lazy load the PageLocal with it, and register the routes.
You can throw out the language column if you like, but lookout for duplicate slugs. Thats why a language prefix is a good idea. (And perhaps it will help with some SEO...)
<?php
$Pages::with('Locals')->all();
foreach($Pages as $Page)
{
foreach($Page->Locals as $PageLocal)
{
Route::get($PageLocal->language.'/'.$PageLocal->slug, $Page->controller);
}
}
And after that you still have to think about url's without a language prefix, get and post routes, etc, etc, but this will get something started.

Magento redirected to other URL after order editting

Currently I'm experiencing a problem after editing orders in the Magento admin. The page is always redirected to another URL, the base of which belongs to the store view that the order belongs to. And this page requires re-login to the admin.
For example, I have two base URLs, each belongs to one store view:
www.example.old.com //old store view (default)
www.example.new.com //new store view
The system uses www.example.old.com as the default base URL. So under www.example.old.com I create an order for the new store and invoice it. Then on submitting the invoice, the page is redirected from
http://www.example.old.com/index.php/admin/sales_order_invoice/new/order_id/1234/
to
http://www.example.new.com/admin/sales_order/view/order_id/1234/
And it requires login for another time.
I traced the redirection code to Mage_Core_Model_Url
public function getRouteUrl($routePath=null, $routeParams=null)
...
$url = $this->getBaseUrl().$this->getRoutePath($routeParams);
public function getBaseUrl($params = array())
....
if (isset($params['_store'])) {
$this->setStore($params['_store']);
}
....
return $this->getStore()->getBaseUrl($this->getType(), $this->getSecure());
Then I don't know what to do. There is no parameter _store but it seems that Magento determines which store view to run based on the order being treated, when it is supposed to stay on the same base URL throughout the admin.
Have you tried to enable customer data sharing between the stores in the backend?
Sorry for newbie answer, still learning magento
For those who may still show interests to this old entry, I share my solution. It is not a good one, indeed it is a hard-coded redirection to avoid going back to an uncertain URL, but it fixed the problem for me.
In the controller action where the redirection happens, modify
$this->_redirect(..., array(... => ...));
to
$this->_redirect(..., array(... => ..., '_store' => Mage::app()->getStore($storeId)));
This ensures that the redirection always goes to the specified store.
Reason is that Magento switchs context to store of order because it requires to translate the email template correctly.
Look at class Mage_Core_Model_Template there are two method _applyDesignConfig and _cancelDesignConfig. First function switches context and remember old context, second function should return all back. But, there is a bug. See more at: http://www.magthemes.com/magento-blog/magento-142-multiwebsite-admin-redirect-problem-quick-workaround/#comment-1084

Resources