Global and Route middleware in Laravel

Laravel Middleware concept from Scratch 

Global and Route Middleware in Laravel

Laravel Middleware provide a filter as well as it act as interface or Middle-Man between HTTP request and response which access the application. Middleware is a way to filter all the bad or Forgery request which try to access your Application.

Laravel Middleware Type 
  • Global Middleware 
  • Route Middleware

Before using any middleware you have to register in Kernal.php. Go to App\Http laravel project Directory, There Kernel.php file is there which have all the Global, Route middleware configure by default for you. If you want to use your custom Middleware you must register that in any one below category.

Global Middleware act on each HTTP Request which try to access the application. By default, Some Middleware is declared as Global in Kernal.php file. See the code below,
 
 /**      * The application's global HTTP middleware stack.      *      * These middleware are run during every request to your application.      *      * @var array      */ protected $middleware = [
 \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,  \App\Http\Middleware\TrimStrings::class,  \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,  \App\Http\Middleware\TrustProxies::class,
];
 

Route Middleware will act on specified HTTP Request which access the Application.

/**      * The application's route middleware.      *      * These middleware may be assigned to groups or used individually.      *      * @var array      */ protected $routeMiddleware = [ 
 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,  'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,  'can' => \Illuminate\Auth\Middleware\Authorize::class,  'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,  'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,   
];
 
Route Group Middleware is another categories where sometime you need to apply the middleware on group of route. At that time you must have to register your Middleware in Kernal.php. See the below code of Kernal.php

/**      * The application's route middleware groups.      *      * @var array      */ protected $middlewareGroups = [ 
  'web' => [   \App\Http\Middleware\EncryptCookies::class,   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,   \Illuminate\Session\Middleware\StartSession::class,   \Illuminate\View\Middleware\ShareErrorsFromSession::class,   \App\Http\Middleware\VerifyCsrfToken::class,   \Illuminate\Routing\Middleware\SubstituteBindings::class,         ],         'api' => [             'throttle:60,1',             'bindings',         ],     ];
  
 

How to Create Middleware in Laravel


You can create your own custom Middleware for your usage. Below is Artisan Command for creating middleware.

php artisan make:middleware MiddlewareName

Lets Create one Custom Middleware named with  MyCustomMiddleware

php artisan make:middleware MyCustomMiddleware

Below is the code sample by default in MyCustomMiddleware

  class MyCustomMiddleware {     /**      * Handle an incoming request.      *      * @param  \Illuminate\Http\Request  $request      * @param  \Closure  $next      * @return mixed      */     public function handle($requestClosure $next)     {         return $next($request);     } }  

Once the custom Middleware is created we must register in the Kernnal.php in App\Http\ Project directory.

Register Custom-Middleware as Global

Register MyCustomMiddleware  as a Global Middleware in kernal.php file and you can use that on route. Below code is the Example to register as global.


 
 /**      * The application's global HTTP middleware stack.      *      * These middleware are run during every request to your application.      *      * @var array      */ protected $middleware = [
 \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,  \App\Http\Middleware\TrimStrings::class,  \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,  \App\Http\Middleware\TrustProxies::class,
 \App\Http\Middleware\MyCustomMiddleware::class,
];
 

In the above Global Middleware we have declare our MyCustomMiddleware, Now each HTTP request which will try to access the Application, will be passed and verified through this middleware. When we register our Middleware ware as a global in Kernal.php, Each HTTP Request will be filtered with this Global Middleware.

Register Custom-Middleware as Route Specific

Register MyCustomMiddleware in Kernal.php as a route specific middleware.

/**      * The application's route Specific middleware.      *      * These middleware may be assigned to groups or used individually.      *      * @var array      */ protected $routeMiddleware = [ 
 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,  'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,  'can' => \Illuminate\Auth\Middleware\Authorize::class,  'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,  'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
 'myCustom' => \App\Http\Middleware\MyCustomMiddleware::class, 
];

Route specific Middleware will be applied on Specific route. So each HTTP request made on the specific route will be filtered and access to the application.

Register Custom-Middleware as Route Group Specific

Register Group Specific Route middleware in kernal.php. This we can apply on group of  route like admin section Route or etc. 

/**      * The application's route middleware groups.      *      * @var array      */ protected $middlewareGroups = [ 
  'web' => [   \App\Http\Middleware\EncryptCookies::class,   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,   \Illuminate\Session\Middleware\StartSession::class,   \Illuminate\View\Middleware\ShareErrorsFromSession::class,   \App\Http\Middleware\VerifyCsrfToken::class,   \Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\MyCustomMiddleware::class,
         ],         'api' => [             'throttle:60,1',             'bindings',         ],     ];

Apply Middleware on Laravel Route file

In Laravel middleware act on the HTTP Request, and the HTTP Request is made through route. So after registering the Middleware in Kernel.php, now we will see how to apply the custom-middleware on route.
/* Below Example is the Example of Route Specific Middleware Declaration */  
Route::get('/'function () {     return view('welcome'); })->middleware('myCustom');

 /* Group Route Specific Middleware Example  */ Route::group(['prefix' => 'admin' , 'middleware' =>['web']], function () { Route::get('user-login','UserController@userLogin'); Route::post('user-verify','UserController@userVerify');
 });

Uttarakhand Objective gk Question in English

Uttarakhand Objective GK Question






  1. The devastating flood which is known as Himalayan Tsunami was occured in the year
    1. A. 2010     
    2. B. 2012      
    3. C. 2013        Correct Answer
    4. D. 2014      
  2.  

    Which city is also known as the "Yoga Capital of the World"
    1. A. Dehradun     
    2. B. Nainital      
    3. C. Haridwar      
    4. D. Rishikesh        Correct Answer
  3.  

    Total number of National Parks in Uttarakhand
    1. A. 5     
    2. B. 7        Correct Answer
    3. C. 8      
    4. D. 10      
  4.  

    What is the literacy rate of Uttarakhand according to 2011 census
    1. A. 73.81 %     
    2. B. 75.32 %      
    3. C. 79.63 %        Correct Answer
    4. D. 79.90 %      
  5.  

    Besides Hindi, which one is the other official language of Uttarakhand
    1. A. English     
    2. B. Sanskrit        Correct Answer
    3. C. Nepali      
    4. D. Urdu      
  6.  

    Total number of districts in Uttarakhand
    1. A. 10     
    2. B. 12      
    3. C. 13        Correct Answer
    4. D. 15      
  7.  

    Who was the first Chief Minsiter of Uttarakhand
    1. A. B. S. Koshyari     
    2. B. N. D. Tiwari      
    3. C. Nityanand Swami        Correct Answer
    4. D. B. C. Khanduri      
  8.  

    Which one is the highest mountain in Uttarakhand
    1. A. Nanda Devi       Correct Answer
    2. B. K2      
    3. C. Kangchenjunga      
    4. D. Chimborazo      
  9.  

    Which river passed through the Valley of Flowers
    1. A. Alaknanda River     
    2. B. Bhagirathi River      
    3. C. Ramganga      
    4. D. River Pushpawati        Correct Answer
  10.  

    In which district, the Jageshwar temple is located
    1. A. Dehradun     
    2. B. Chamoli      
    3. C. Haridwar      
    4. D. Almora        Correct Answer
  11.  

    The Char Dham Yatra begins every year in the month of
    1. A. April     
    2. B. May        Correct Answer
    3. C. September      
    4. D. December      
  12.  

    In which year Uttarakhand was established as a separate state
    1. A. 1998     
    2. B. 2000        Correct Answer
    3. C. 2001      
    4. D. 2003      
  13.  

    Which one is the largest district by area wise in Uttarakhand
    1. A. Uttarkashi       Correct Answer
    2. B. Pithoragarh      
    3. C. Pauri Garhwal      
    4. D. Nainital      
  14.  

    At Dev Prayag, the Bhagirathi river meets with the
    1. A. Nandakini River     
    2. B. Mandakini River      
    3. C. Alaknanda River        Correct Answer
    4. D. Ganga River      
  15.  

    In which year, the Chipko Movement was awarded with the Right Livelihood Award
    1. A. 1987       Correct Answer
    2. B. 1990      
    3. C. 1994      
    4. D. 1998      
  16.  

    The Treaty of Sugauli took place in the year
    1. A. 1801     
    2. B. 1805      
    3. C. 1811      
    4. D. 1815        Correct Answer
  17.  

    According to 2011 census, which district of Uttarakhand had negative population growth rate
    1. A. Pithoragarh     
    2. B. Almora        Correct Answer
    3. C. Rudraprayag      
    4. D. Uttarkashi      
  18.  

    Which one is the largest glacier in Uttarakhand
    1. A. Bandarpunch Glacier     
    2. B. Dokriani Glacier      
    3. C. Gangotri Glacier        Correct Answer
    4. D. Pindari Glacier      
  19.  

    The Uttarakhand High Court is located at
    1. A. Nainital       Correct Answer
    2. B. Haldwani      
    3. C. Dehradun      
    4. D. Rishikesh      
  20.  

    Which lake of Uttarakhand is also known as "mystery lake"
    1. A. Nainital     
    2. B. Sattal      
    3. C. Roopkund        Correct Answer
    4. D. Naukuchiatal      
  21.  

    'Pinder River' joins Alaknanda at
    1. A. Vishnu Prayag     
    2. B. Joshi Math      
    3. C. Rudra Prayag      
    4. D. Karna Prayag        Correct Answer
  22.  

    Which one of the following is a biosphere reserve in Uttarakhand
    1. A. Gobind     
    2. B. Corbett      
    3. C. Rajaji      
    4. D. Nanda Devi        Correct Answer
  23.  

    Which Queen is also known as "Nakati Rani" in Garhwal
    1. A. Guleria Rani     
    2. B. Karnavati Rani        Correct Answer
    3. C. Nepalia Rani      
    4. D. kamlendumati Rani

Laravel Eloquent ORM Query and Model Feature

Laravel Eloquent ORM Query from Scratch

Laravel Eloquent feature is object Oriented paradigm approach of database communication. In Eloquent we create Model for each Table in the database, which set the communication (Fetching, Inserting, Deleting, Modifying the Record ) with database.

You can create the Model with Migration or without migration with the help of Artisan Command. We can use -m or --migration after the artisan command to create the Model with Migration. Below code  is the Example.

Eloquent Model with Database Migration


Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

                  php artisan make:model model-Name  --migration (--migration is for migration )

This above two Artisan Command will create Table migration file in your databaese / migration directory which you can modify further.

Create Model without Migration. Below is the Artisan command to create Model.

  php artisan make:model model-Name 

Lets Take Example, We will create Model Named with CategoryMaster 


php artisan make:model CategoryMaster  -m


This above Artisan Command will create the Model named with CategoryMaster.  Below is the code for your reference   

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CategoryMaster extends Model
{     // }

Eloquent Model Property


In the above model, we didn't mention the table. So we have to declare the table in CategoryMaster Model.

protected  $table = '"category_table";

In Eloquent Model, Eloquent consider by default each table has a primary key id with incrementing integer Value. How to Define a protected Primary key property:

protected  $primaryKey = '"id";

protected  $incrementing = '"false";

if Primary Key is not an integer then you must set the KeyType a string.

protected $keyType = 'string';

Once the Table is declared in the Model, By Default timestamp (Created_at, updated_at) will be true. If you don't want them then you have to set the timestamp to false.

protected $timeStamp = "false";

Eloquent Model and Database Connection


Eloquent model will use Default Database which got configured with your laravel Application. if you wish to have your model connected with other database then you have to use $connection Property. Code is below for your reference.

protected $connection = "Connection-Database-Name"; 

Fetch / Retrieve Model In Eloquent

Once the Model is Created with Associated table, We can perform all the database operation(CRUD) on it. We will Query / fetch database table associated with model step by step.

Above we have created CategoryMaster  Model, Now we will use this model for writing our Eloquent Query as a Example.

$data= App\CategoryMaster::all();

all() method in Eloquent will return all result from the specified model table. We can use various constraint on the all method to filter the table record.

$data = App\CategoryMaster::where('status', 1)->orderBy('id', 'desc')
        ->take(5)->get();

As Eloquent is Query Builder you can use all the Query Builder method for database Operation.


Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post