MariusP
MariusP

Reputation: 492

Laravel resourceful controller - differentiate an API call from a browser

I have a single route defined like this:

Route::resource('problem', 'ProblemController');

The moment I POST to /problem, a ProblemController@store method is fired.

Now what I want is to return a JSON response if it's an API call or a view (or maybe redirect) if I'm on the "web-side" of my application. How can I approach this problem?

Should I create separate controllers? Should I (in every method/controller) detect the type of the request and respond accordingly? Should I use middlewares? Route groups? Separate application?

The main goal is to have multiple application types (API + versioning + web) in one package but share the business logic, models and most of the code (to avoid repeating).

I am using Laravel 5.2.

Thank you!

Upvotes: 1

Views: 2442

Answers (2)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

Request object offers a method wantsJson() that checks Accept header of the request and returns TRUE if JSON was requested.

In your controller you can do the following:

if( request()->wantsJson() )
{
    return ['foo' => 'bar'];
}

return view('foo.bar');

You can read more about content negotiation in Laravel here: http://fideloper.com/laravel-content-negotiation

Upvotes: 6

Jeff
Jeff

Reputation: 25221

You can create a route group like this:

Route::group(['prefix'=>'api'], function(){
    //All routes in this route become domain.com/api/route
});

This makes the most sense to me because a route that returns a view and an API route are two separate things. You should have a controller for the pages and views you want to show in your app, and another one for the api routes that update and change your data, returning JSON.

Upvotes: 1

Related Questions