Ajax Middleware

后端 未结 1 1659
一个人的身影
一个人的身影 2021-01-12 04:19

I seem to remember in Laravel 4 there was an ajax filter, this would only allow requests via ajax.

Is there any similar middleware for Laravel 5.

I have a ro

相关标签:
1条回答
  • 2021-01-12 04:50

    You can use a middleware to do that.

    php artisan make:middleware AllowOnlyAjaxRequests

    app/Http/Middleware/AllowOnlyAjaxRequests.php

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

    Add 'ajax' => \App\Http\Middleware\AllowOnlyAjaxRequests::class, to your routeMiddleware array in app/Http/Kernel.php.

    Then you can use ajax middleware on your routes.

    0 讨论(0)
提交回复
热议问题