Inigo
Inigo

Reputation: 8685

Laravel: middleware to determine which controller to use

I am building a site which loads all pages and content via javascript while also manipulating the browser address bar (giving the illusion of a normal, navigable site with each page at its own URL). As a fallback, and for the benefit of search engines, the pages must also be able to be loaded normally at their respective URLs.

To do this, I need to let Laravel know if the page data is being requested via an ajax call or normal HTTP request. This- I presume- would be a situation where I would use Middleware. I want to be able to process the pages using two different controllers; one for ajax, one for HTTP.

ie:

if (Request::ajax()){
    forward request to ajax page controller
}else {
    forward request to standard page controller
}

Is this possible to handle with middleware? All examples I can find seem to assume that the controller is already a given.

Upvotes: 3

Views: 840

Answers (1)

whoacowboy
whoacowboy

Reputation: 7447

I use the routes.php file instead of middleware. I believe middleware is after the route has been determined.

if(Request::ajax() || Request::json()){
    Route::get('items', [
        'as' => 'api.posts.index' ,
        'uses' => 'Api\ItemsController@index'
    ]);
} else {
    Route::get('items', [
        'as' => 'posts.index' ,
        'uses' => 'ItemsController@index'
    ]);
}

I do it this way because I like to separate out the urls for json versus web.

Route::get('items', [
    'as' => 'posts.index' ,
    'uses' => 'ItemsController@index'
]);

/**
 * JSON API
 *
 */
Route::group([
         'prefix' => 'api/v1', 
         'as' => 'api.', 
         'namespace' => 'Api'
      ], function () {

    Route::get('items', [
        'as' => 'posts.index' ,
        'uses' => 'ItemsController@index'
    ]);

}

Either way your controllers would live here.

App/Http/Controllers/Api/ItemsController.php
App/Http/Controllers/ItemsController.php

EDIT

I read the comment form GONG and the RouteServiceProvider would also work for this, but you would still have two distinct urls. You would have to manage another routes file, but whatever works for you.

Upvotes: 1

Related Questions