Showing posts with label laravel route middleware. Show all posts
Showing posts with label laravel route middleware. Show all posts

Laravel Routing and Named Route with Example

laravel Route List and Resource

Concept of Laravel Routing, Resource and list


Laravel Routes are defined in web.php file which is called by default and resides in routes directory. URL prefix is applied directly and automatically in laravel, you don't have to apply the prefix to each route individually. Router methods list are available like get, post, put, patch, delete, any. 

Any form request which point to Route method like post, put, patch, delete you must have to include the csrf token field.

Basic Route Example :

Route::get('/', function () {
    return 'Welcome to Laravel Basic Routing.';
});

Route::get('/user-profile', 'ProfileController@showProfile');

Redirecting Route to another Route in Laravel

Laravel provide redirect route to another route facility. if you want to redirect the one route to another route. Route redirect return 302 status by default, we can customize the status code using third parameter. See the below code for above two statement.

Route::redirect(' /one-route ', '/other-route');
Route::redirect(' /one-route ', '/other-route', 301);

View Route in Laravel

Route::View method is one useful method in laravel which we can use if we want to show the view only. This provide the shortcut way to redirect the route to view without defining all the route and controller. 

Route::view method accepts three parameter, one is URL string, second argument is view name and third argument is some additional parameter as a array. Below is the code for reference.

Route::view('/my-profile', 'user-profile');
Route::view('/my-profile', 'user-profile', ['name' => 'Umesh']);


Laravel Named Route


Named Route is a friendly name given to the route the reference. We can use Named rout to specify the particular Route as well as to generate the URL / to redirect to specific URL.

Route::post('profile-data/save', 'ProfileController@saveProfile')
->name('profileData');

You must keep the route name always unique. Generating / Redirecting Url for Names Route is below for your reference.

$url = route('profile');
return redirect()->route('profile');

With Name Route we can pass the second or third parameter as a argument.

Route::post('profile-data/{id}', 'ProfileController@updateProfile')
->name('profileData');

To pass the parameter as argument in the named Route code is below for your reference.

$url = route('profile', ['id'=>1 ]);

If we pass the additional parameter in the array, that will be automatically added in the URL generated query String. Below is the example for reference.

$url = route('profile-data/{id}', ['id' => 1, 'rollno' => '1004']);
URL String generated is below /1/profile?rollno=1004

Laravel Route Prefix Defination

Laravel prefix method can add the prefix to the group of route with given URL. Simple example is most of the web application have the admin section. Now as a developer I want to add admin as a prefix to all the route which point to admin pages. Below is the code for your reference.

Route::prefix('admin')->group(function () {
   
        // You have to define all your route here.
    
});

Apply Middleware on Route

We can assign the middleware to the group of route in the routes Directory. As we know that Middleware act as the middle man between the HTTP request and Application,  it filter and restrict the unwanted HTTP request to access the application. Below is the code for reference.

Route::middleware(['AdminMiddleware', 'AuthMiddleware'])->group(function () {
    
 // Specify All the route in this group.
 
});

Laravel Fallback Route

Route::fallback method is another feature of  Laravel Routing in which we handle the HTTP request which do not match with our route list. By default laravel render the 404 not found page using exception handler. Now laravel fallback method you can define and redirect to the view which will get execute if not HTTP request matches.

You must always define the Route::fallback method at the last of route file. Below is the code for your reference.

Route::fallback(function() {
    return 'You have landed on wrong url. ';
});

Current Route Access  

We can Access the current route which is handling the HTTP request  using current,  currentRouteName and currentRouteAction methods. Below is the code example for your reference.

$currentRoute = Route::current();
$routeName = Route::currentRouteName();
$routeAction = Route::currentRouteAction();

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');
 });

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