Search code examples
ajaxlaravel-5laravel-request

Authorize a form request only if it an ajax call


I have a form that i want to authorize only if the call was made by ajax, so i tried

....
//MyRequest authorize function
public function authorize()
{
    return $this->ajax();
}

But after when i do the ajax call, in the console it shown "This action is unauthorized.", so how can i detect if the call was an ajax and return true, else return false?


Solution

  • This is a job for middlewares.

    php artisan make:middleware IsAjaxRequest
    

    In app/Http/Middleware/IsAjaxRequest.php

    <?php
    
    namespace App\Http\Middleware;
    
    class IsAjaxRequest
    {
        public function handle($request, \Closure $next)
        {
            // Check if the route is an ajax request only route
            if (!$request->ajax()) {
                 abort(405, 'Unauthorized action.');
            }
    
            return $next($request);
        }
    }
    

    Don't forget to also register your middleware in app/Http/Kernel.php by adding the following in the $routeMiddleware array.

    'ajax' => \App\Http\Middleware\IsAjaxRequest::class
    

    Then you can add it to any route handling an Ajax call

    Route::get('users', 'UserController@method')->middleware('ajax');