Wednesday, March 15, 2017

How to return different output formats from the same controller method in Laravel?

I want to set up the proper routes and models so when I visit www.myapp.com/search?keyword=test I get a view with data and when I visit api.myapp.com/search?keyword=test I get JSON representation of the exact same search result.

If I sort out the subdomain routes like so:

Route::group(array('domain' => '{subdomain}.myapp.com'), function()
{
    Route::get('/', function($subdomain)
    {
        dd($subdomain);
    });
});

What's the simplest way to use the same model method but instead of returning a view (for non-subdomain routes) with the array of model objects like so:

return view('search', compact('models'));

I'd return an array of JSON objects, simply like so:

return $models;

Note: a subdomain is not that necessary, it can also be myapp.com/api/search?keyword=test

Thanks.



via Shareb

Advertisement