如何Laravel阻止/重定向直接访问Ajax路由?
我创建了Middleware OnlyAjax.php
<?php
namespace App\Http\Middleware;
use Closure;
class OnlyAjax
{
public function handle($request, Closure $next)
{
if ( ! $request->ajax())
return redirect()->route('admin.dashboard');
return $next($request);
}
}
添加Karnel.php
'ajax' => \App\Http\Middleware\OnlyAjax::class,
我的路线
Route::middleware(['ajax'])->group(function () {
Route::group(['middleware' => ['roles'], 'roles' => [1, 2, 3, 4]], function () {
Route::post('select-plan', 'AjaxController@selectPlan')->name('ajaxSelect.plan');
});
});
但是我出错了
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
当我将Route::post
更改为Route::get
时,它可以正常工作。但我想使用Route::post
答案 0 :(得分:1)
已定义2方法,并在控制器上决定如何处理流量。
Route::match(array('GET','POST'),'select-plan', 'AjaxController@selectPlan')->name('ajaxSelect.plan');
并在控制器中。
if (Request::isMethod('get')){
// redirect user
}
if (Request::isMethod('post')){
// do logic for post method
}