仅在 ajax 调用时授权表单请求

Authorize a form request only if it an ajax call

我有一个表格,只有当 ajax 调用时我才想授权,所以我尝试了

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

但是在我调用 ajax 之后,在控制台中它显示 "This action is unauthorized.",那么我如何检测调用是 ajax 和 return true,否则 return false?

这是 middlewares 的工作。

php artisan make:middleware IsAjaxRequest

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

别忘了在 app/Http/Kernel.php 中注册您的中间件,方法是在 $routeMiddleware 数组中添加以下内容。

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

然后您可以将它添加到任何处理 Ajax 调用的路由

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