title: Best way to write same code for both (web and API) with different type of response?
body: <p>I am working on a laravel project where I have to write code for web-app as well as APIs with same business logic. </p>
  
  <p>Since there is no difference in business logic so I am thinking to write code in traits and use them in different controllers and send response according to request headers. In this way same code will serve both web-app and mobile apps.</p>
  
  <p>Using traits I can write different routes and make different controllers for web and APIs easily.</p>
  
  <p>For example</p>
  
  <pre><code>In web.php
  Route::get('users','UsersController@index');
  In api.php
  Route::get('users','Api\UsersController@index');
  </code></pre>
  
  <p>And then using trait I can write only one function called index or any other name like shown below.
  For now I check if request wants json using wantsJson() method of Request class.</p>
  
  <pre><code>public function index(Request $request){
       $users = User::all();
  
      if($request-&gt;wantsJson()){
         return response()-&gt;json(['users',$users]); 
      }
      return view('uses.index',compact('users'));
  }
  </code></pre>
  
  <p>Is there any better way to accomplish this ?</p>