Laravel route group has many important aspect. It saves you time for certain actions you want to. It helps you if you want to make a multiple language website.
For example if you want to have a website where you to change the languages from the front end site of the website.
Syntax
First understand the basic syntax of route group
Route::group( [ ] , callback);
So route::group takes a array and callback function. Within the array you can mention
and many other things.
Defining Groups
// web.php
Route::namespace('Admin')->group(function() {
Route::resource('users', 'UserController');
});
And within the callback we generally mention the routes. In this we created a resourceful route.
For this kind of changes, we need to create different name spaces. We could do that when we create controller. We will create two different folders. One is for English and another is for Chinese language.
Example
First we will create the folders in app/Http/Controller. Names are En and Zh. En for English language and Zh for Chinese language.
Then we will create controllers for each of this folder.
php artisan make:controller En/IndexController
The above command will create IndexController under app/Http/Controllers/En. Here En is also our namespace, we would be able to use this name space in our route grouping
Route::group(['namespace' => ‘En'], function() {
//your routes go here for index controller
});
Now within this Route group we write our routes
Now within IndexController we can have many different methods and those methods could be mentioned as routes in the.
Then we will create a route group for our chinese language routes. First we will do
php artisan make:controller Zh/IndexController
and then in the web.php we will add
Route::group(‘[namespace’=>’Zh’], function(){
//index controllers routes go here
});
And Now in IndexController (located under app/Http/Controllers/), we need to mention our namespace for En. So it should be
namespace App\Http\Controllers\En;
We can do the similar for our chinese language IndexController
namespace App\Http\Controllers\Zh;
See the picture for web.php
We need to make a change in RouteServiceProvider.php file. Find and make the changes. Mention the controllers namespace there. You may just uncomment protected $namespace
Because of this, web.php file would know where to find the controllers for each route.
With this we are done. We need another last step. In ther resources/view folder we may need to create a folder for chinese language view. and we will put the blade files there for chinese language.
So route groups really make your multilanguage development much faster.