Laravel prevent direct access to ajax route

How do you prevent a user from directly access the route and retrieving the data.

It is an ajax request.

I’ve created a route

Route::get('/getmodels/{make_id}', ['as' => 'ajax.get.models', 'uses' => 'DashboardController@getModelsFromMake']);

In my kernel i’ve pointed the middleware to the named route ‘ajax.get.models’
in the routeMiddleware array.

'ajax.get.models' => 'AppHttpMiddlewareRedirectIfNotAjax’,

In RedirectIfNotAjax i have this. Im not sure if i’m approaching this correctly.

public function handle($request, Closure $next)
    if (!$request->ajax()) {
        return redirect()->to('/');

    return $next($request);


Im not sure how do i prevent the user from accessing the url via the browser directly like

Source: laravel

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.