0

How to Laravel block/redirect direct access to ajax route?

I created 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);
    }
}

Add in Karnel.php

'ajax' => \App\Http\Middleware\OnlyAjax::class,

My Route

Route::middleware(['ajax'])->group(function () {
            Route::group(['middleware' => ['roles'], 'roles' => [1, 2, 3, 4]], function () {
                Route::post('select-plan', 'AjaxController@selectPlan')->name('ajaxSelect.plan');
            });
        });

But I got error

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

No message

When I change Route::post to Route::get it's working. But I want to use Route::post

2
  • Try using $request->wantsJson() Commented Mar 6, 2019 at 12:39
  • $request->wantsJson() Not working Commented Mar 6, 2019 at 12:42

1 Answer 1

1

Have the 2 method defined and on the controller decide what to do with the traffic.

Route::match(array('GET','POST'),'select-plan', 'AjaxController@selectPlan')->name('ajaxSelect.plan');

and in the controller.

if (Request::isMethod('get')){
    // redirect user
}

if (Request::isMethod('post')){
    // do logic for post method
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.