jeudi 3 septembre 2015

Sending different types of responses based on URL

I have a Laravel application with Eloquent entities and their respective RESTful resource controllers, like the following:

The model

class Entity extends Eloquent {
    ...
}

The controller

class EntityContoller {

    public function index() {
        Entity $entities = Entity::all();
        return view('entity.index', compact($entities));
    }

    ... // And many more routes like that
}

Now I am building an android application, and instead of returning views, I need the data as JSON.

In my current solution, for every request I make from my Android application, I add a get query parameter contentType=JSON. I detect that in the controller, and send the data accordingly like the following. But this seems tedious, and I seem to have to write the same condition everywhere.

class EntityContoller {

    public function index() {
        Entity $entities = Entity::all();
        if(Request::get('contentType', 'JSON')) return $entities;
        return view('entity.index', compact($entities));
    }

    ... // And many more routes like that
}

What is the best way I can do this, without having to write this condition in every controller action?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Ku5hKd
via IFTTT

Aucun commentaire:

Enregistrer un commentaire