Home Laravel How to create ajax middleware in laravel with php artisan command?

How to create ajax middleware in laravel with php artisan command?

by therichpost
Published: Updated: 6 comments
Laravel 7.2 routing with route group auth guard check with prefix

Hello to all, welcome to therichpost.com. In this post, I will tell you, How to create ajax middleware in laravel with php artisan command? I am doing with laravel first time in my website. Laravel is one of the top php mvc framework. Here are the steps in laravel for making middleware: I have done this code in laravel 5.7.

 

1. First you need to write and run below command into your terminal:

php artisan make:middleware AjaxRequestOnly

After run above command, you will find AjaxRequestOnly.php file into your app/Http/Middleware/AjaxRequestOnly.php and you will see below code into this file: I have added ajax code into below file for ajax requests

<?php 
namespace App\Http\Middleware; 
use Closure; 
class AjaxRequestOnly
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->ajax()) {
            return $next($request);
        }
        abort(403, 'Unauthorized Access!');
    }
}

 

2. After this add below code into your app/Http/Kernel.php file:

<?php 
namespace App\Http; 
use Illuminate\Foundation\Http\Kernel as HttpKernel; 
class Kernel extends HttpKernel
{
.... 
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
....
 'ajax'=>\App\Http\Middleware\AjaxRequestOnly::class
];
}

 

3. For check ajax call or support you can assign ajax middleware to particular Route and Controller and below is the example code and you can this code into your routes/web.php file:

Route::post('/addtocartlocation', 'CartController@addToCartLocation')->middleware('ajax');

 

There are so many code tricks in laravel and i will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com

You may also like

6 comments

alexa February 26, 2018 - 4:50 am

Good post..

Reply
therichpost March 21, 2018 - 4:55 am

thank you

Reply
leela June 1, 2018 - 10:58 am

This is easy and simple..working well

Reply
therichpost June 1, 2018 - 5:17 pm

Thank you leela

Reply
jack October 7, 2018 - 4:29 am

Awesome article.

Reply
Ajay Malhotra October 7, 2018 - 8:11 am

Thank you jack..

Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.