Laravel:验证 ajax 请求



在我的 laravel 应用程序中,我正在通过 ajax 请求加载表单。我需要验证每个方法,例如createedit,只是ajax request。但是,如果通过get调用它们,则应使用错误消息重定向它们。

我正在使用以下代码。它工作正常,但我必须在我需要保护的每个方法上写它。

SomeController.php, AnotherController.php,YetAnotherController.php, ...:

public function create()
{
if(!request()->ajax())
{
# setting error message
session()->flash('warning', 'Invalid request method or method not allowed');
# redirecting
return redirect()->route("admin.dashboard");
}
...
}
public function edit()
{
if(!request()->ajax())
{
# setting error message
session()->flash('warning', 'Invalid request method or method not allowed');
# redirecting
return redirect()->route("admin.dashboard");
}
...
}

有没有办法验证应用程序中的每个控制器的指定方法..?

在控制器中.php__construct添加以下内容:

public function __construct ()
{
$ajaxMethods = ['insert', 'update'];
$currentActionMethod = Route::getCurrentRoute ()->getActionMethod ();
if ( in_array ( $currentActionMethod, $ajaxMethods ) AND ! request ()->ajax () )
{
return redirect ()->back ()->with ( 'warning', 'Invalid request method or method not allowed' );
}
}

创建中间件

public function handle($request, Closure $next)
{
$ajaxMethods = ['insert', 'update'];
$currentActionMethod = Route::getCurrentRoute ()->getActionMethod ();
if ( in_array ( $currentActionMethod, $ajaxMethods ) AND ! request ()->ajax () )
{
return redirect ()->back ()->with ( 'warning', 'Invalid request method or method not allowed' );
}
return $next($request);
}

尝试使用中间件,验证它并在控制器的构造函数中调用中间件

将其添加到帮助程序的一种方式,因此您唯一应该做的是首先在助手.php中创建一个验证方法,然后在composer.json的自动加载部分中定义它并完成。 随时随地调用函数。如果您想要示例或对此有疑问,请告诉我

感谢@OmerYILMAZ和其他帮助的人,这是我的最终代码...

app\Http\Middleware\AllowedAjaxRequests.php:

namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesRoute;
class AllowedAjaxRequests
{
/**
* Handle an incoming request.
*
* @param  IlluminateHttpRequest  $request
* @param  Closure  $next
* @return mixed
*/
public function handle($request, Closure $next)
{
# variables
$ajaxMethods   = ['create', 'update'];
$currentAction = Route::getCurrentRoute()->getActionMethod();
# validating request method
if (in_array($currentAction, $ajaxMethods) && !$request->ajax())
{
# setting error message
session()->flash('warning', 'Invalid request method or method not allowed');
# redirecting
return redirect()->route("admin.dashboard");
}
return $next($request);
}
}

app\Http\Kernel.php:

class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
...
'ajaxRequests' => AppHttpMiddlewareAllowedAjaxRequests::class,
];
...
}

路由\网络.php:

Route::middleware(['ajaxRequests'])->group(function() {
...
});

相关内容

  • 没有找到相关文章

最新更新