Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Middleware

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 route which gets data from my database via ajax, I want to protect this route so no user can go to it and see a json string of data.

like image 543
panthro Avatar asked Aug 27 '15 10:08

panthro


1 Answers

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.

like image 198
Can Vural Avatar answered Oct 20 '22 19:10

Can Vural