আগামী ১৫ ডিসেম্বর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML, CSS PHP,MySQL,JavaScript, AJAX, JQUERY, Bootstrap and Live Project কোর্সের ৮৭ তম ব্যাচ এবং ২৬ ডিসেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে চার মাস ব্যাপী Zend PHP-7 Certified PHP Engineering (Advance PHP) কোর্সের ৩৫ তম ব্যাচ। প্রত্যেকটি কোর্স এর ফী নির্ধারণ করা হয়েছে ৩০,০০০/= আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722 81 75 91

Laravel 5.4 Tutorial Part-4: Laravel Route Groups

Laravel Route groups allow you to group several routes together, and apply any shared configuration settings once to the entire group, to reduce this duplication. Additionally, route groups are visual cues to future developers (and to your own brain) that these routes are grouped together and allowing you to keep your code neat and tidy.In reality, you’re actually passing a closure to the group definition, and defining the grouped routes within that closure.

an example of a route group.

Example: A group of routes.

<?php

// routes/web.php
 Route::group([], function () {

 Route::get('/first', function () {
 	echo "I'm First";
 });
 Route::get('/second', function () {

 	echo "I'm Second";
 });
 Route::get('/third', function () {
 	echo "I'm Third";
 });

 });

Sample Output

Route Group

Route Group

We use the group() method, providing an array and closure. Inside the closure, we can define as many routes as we like!

By default, a route group doesn’t actually do anything. There’s no difference between the group and separating a segment of your routes with code comments. The empty array that’s the first parameter, however, allows you to pass a variety of configuration settings that will apply to the entire route group.

Path Prefixes

If many of your routes share a common URL structure, you could use a route prefix to avoid a small amount of repetition. Take a look at the following example:

<?php

 // routes/web.php
 Route::group(['prefix' => 'books'], function () {
// First Route
Route::get('/first', function () {
return 'The Colour of Magic';
 });
// Second Route
Route::get('/second', function () {
return 'Reaper Man';
 });

// Third Route
Route::get('/third', function () {
 return 'Lords and Ladies';
 });

});

Using the prefix array option of the route group, we can specify a prefix for all of the URIs defined within the group. For example, the three routes above are now accessible at the following URLs.

Example: The prefixed URLs.

/books/first

/books/second

/books/third

Use route prefixes to avoid repetition within your routes, and to group them by purpose for organizational or structural value.

Route Group with Prefix

Route Group with Prefix

Subdomain Routing

Laravel Subdomain routing is the same as route prefixing, but it’s scoped by subdomain instead of route prefix. If we use modern applications eg. wordpress, shopify, usually after signup we have our own subdomain for example masud.wordpress.com, masud.shopify.com, etc. In laravel, we can create features using Routing subdomain. Syntax essentially as follows:

Route :: group ([ 'domain' => '{account} .domain.com'], function () 
{
  Route :: get ( 'user / {id}', function ($ account, $ id) 
  { 
    // 
  }); 
});

For example, we create a website fakebook.dev in our local server, and it receive a sub-domain with username.
If we access masud.fakebook.dev it will display the page account Masud
If we access masud.fakebook.dev/profile it will display the profile Masud
If we access masud.fakebook.dev/status/1 it will display the status of Masud with id 1

Step 1: Create virtual host and sub-domain


First we create a virtual host called fakebook.dev in our localhost host, that displays the user account information. To make it we need prepare your `fakebook.dev`, because the local host is not allowed to create a sub-domain, we need to add a domain for each user manually.

Let us create a virtual host called fakebook.dev and sub-domain called “masud” we add the following line in our hosts file

file: C: \ Windows \ System32 \ Drivers \ etc \ hosts

        127.0.0.1       localhost
	127.0.0.1      	fakebook.dev
	127.0.0.1      	masud.fakebook.dev
        127.0.0.1      	sohel.fakebook.dev
	::1             localhost

Step 2: Configure Apache :

Now Edit the Apache configuration file to accept Virtual Hosts and define the particular Virtual Hosts you want to setup on your computer.

File Path : /apache/conf/extra/httpd-vhosts.conf
Add Following code in httpd-vhosts.conf file

<VirtualHost *:80>
DocumentRoot "C:\xampp\htdocs\blog\public"
ServerName fakebook.dev
<directory "C:\xampp\htdocs\blog\public">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from all
</directory>
</VirtualHost>

Step 2: Add Subdomain Routing Code

Now Add following code in your routes/web.php file:

Route::group(['domain' => 'fakebook.dev'], function()
    {
    Route::any('/', function()
    {
        return 'My own domain';
    }); 
}); 

Route::group(['domain' => '{username}.fakebook.dev'], function()
{
    Route::any('/', function($username)
    {
        return 'You visit your account: '. $username; 
    });
});

Once ready, Restart your xampp apache server and let’s check your virtual host with Laravel:

Laravel Virtual Host Example

Laravel Virtual Host Example

And Now Check Your Subdomain Example:

Laravel Subdomain Routing Example

Laravel Subdomain Routing Example

Step 3: Display User Profile with Laravel Subdomain and Group Routing Feature

For simplicity, let’s save all user data in the array. Then, we are passing this array to closure on route to display profile. So that the route turns into : routes/web.php file:

Route::group(['domain' => 'fakebook.dev'], function()
    {
    Route::any('/', function()
    {
        return 'My own domain';
    }); 
}); 

Route::group(['domain' => '{username}.fakebook.dev'], function()
{

	 Route::any('/', function($username)
    {
        return 'You visit your account: '. $username; 
    });

	$data_user = [ 
    'masud' => [ 
       'profile' => ' a cute programmer. ', 
       'status' => [ 'I\'m cool!', 'I\'m cool very Cool!', 'Fantastic!'] 
     ], 
    'sohel' => [ 
       'profile' => 'a boss programmer.' , 
       'status' => [ 'Sweet!', 'Today is incredible!', 'Nice ..'] 
     ] 
  ];

   Route :: get ( 'profile', function ($username) use ($data_user) 
  { 
    return $username." is a ".$data_user[$username] [ 'profile']; 
  }); 
});

And Now Check Your User Subdomain and User Profile Example:

User Profile with Subdomain in Laravel Route

User Profile with Subdomain in Laravel Route

Step 4: Displaying User Status:

To display user status, we will also use the array that was created earlier. Add the following route:


Route::group(['domain' => 'fakebook.dev'], function()
    {
    Route::any('/', function()
    {
        return 'My own domain';
    }); 
}); 

Route::group(['domain' => '{username}.fakebook.dev'], function()
{

	 Route::any('/', function($username)
    {
        return 'You visit your account: '. $username; 
    });

	$data_user = [ 
    'masud' => [ 
       'profile' => ' a cute programmer. ', 
       'status' => [ 'I\'m cool!', 'I\'m cool very Cool!', 'Fantastic!'] 
     ], 
    'sohel' => [ 
       'profile' => 'a boss programmer.' , 
       'status' => [ 'Sweet!', 'Today is incredible!', 'Nice ..'] 
     ] 
  ];


   Route :: get ('status/{id}', function ($username, $id) use ($data_user) 
  { 
    return $username. ' writes: '. $data_user [$username] ['status'] [$id]; 
  }); 

});

Let’s try to check the status Masud:

User Status with Subdomain in Laravel Route

User Status with Subdomain in Laravel Route

User Status with Subdomain in Laravel Routes

User Status with Subdomain in Laravel Routes

Namespace Prefixes

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace parameter in the group array.

As an example lets use the namespace array attribute.

Say we have a controller called NewsController that contains all the Admin logic for your apps news section. You may place this file within the ‘App/Http/Controllers/Admin` directory.

Create Laravel Controller in a folder

Create Laravel Controller in a folder



Laravel 5X follows PSR-4 autoloading conventions, so the application expcets the namespace to be identical to the path of the file, so our class might look something like this:

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NewsController extends Controller
{
    //
}

We could write a route to this class like so:

Route::get('admin/news', [
    'uses' => 'Admin\[email protected]'
]);

Controller Output

Controller Output

Note: Laravel automatically assumes all your controllers will be in the App/Http/Controllers directory so we can leave this out of any controller declarations in the routes file.

The above should work fine, but maybe you also have a dozen or so other class files that deal with Admin logic all within the same namespace. We can use the namespace option to group these together.

Route::group(['namespace' => 'Admin'], function()
{
    Route::get('admin/news', [
        'uses' => '[email protected]'
    ]);

    Route::get('admin/users', [
        'uses' => '[email protected]'
    ]);

});

Notice how I no longer define the Admin namespace for the controller for each route.

The same process can be applied to middleware, subdomains, and url prefixes.

Name Prefixes

Lets take the first example and build on it. As you can see from the above route declarations all our admin routes share a common url prefix.

http://fakebook.dev/admin/news
http://fakebook.dev/admin/users

We can use the prefix array attribute to define the common url for our routes. In our case this is admin.

Our updated Route declarations would look like so.

Route::group(['namespace' => 'Admin', 'prefix' => 'admin'], function()
{
    Route::get('news', [
        'uses' => '[email protected]'
    ]);

    Route::get('users', [
        'uses' => '[email protected]'
    ]);

    ...
});

Your probably wondering why would this be useful? Well imagine you have developed a large application with tens if not hundreds of routes. Then one day your boss comes to you and says “Hey Mr. tester, we need to change the admin url from /admin to /cms, how long will this take?”.

If you’ve declared all your routes using groups with the prefix array attribute like above, this is going to be an easy and painless process for you.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now i’m a founder and CEO of TechBeeo Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

Leave a Reply

Your email address will not be published. Required fields are marked *