在RESTfulAPI和Laravel应用程序中区分web和移动请求

在RESTfulAPI和Laravel应用程序中区分web和移动请求,rest,laravel-5.3,restful-architecture,Rest,Laravel 5.3,Restful Architecture,我正在Laravel 5.3中开发一个应用程序,我正在为它实现RESTful API,并且我正在尽可能避免服务器端的冗余代码,例如,我需要移动应用程序和web应用程序向同一url发送请求 例如,用于更新类别 public function update($categoryId) { //some code here } 移动应用程序和web应用程序都会向上述功能发送更新类别的请求,该功能位于CategoryController 问题:我需要找到一种标准方法来处理不同类型的请求,

我正在
Laravel 5.3
中开发一个应用程序,我正在为它实现RESTful API,并且我正在尽可能避免服务器端的冗余代码,例如,我需要移动应用程序和web应用程序向同一url发送请求

例如,用于更新类别

public function update($categoryId)
{
    //some code here   

}
移动应用程序和web应用程序都会向上述功能发送更新类别的请求,该功能位于
CategoryController


问题:我需要找到一种标准方法来处理不同类型的请求,例如web请求应重定向到新页面,但在移动请求的情况下,仅应将
JSON响应
发送回移动应用程序。在
控制器
中区分这些请求的标准和正确方法是什么,以了解哪个请求是从哪个设备发送的

如果调用的
update
功能与web/mobile应用程序不同,只需传递另一个参数,然后在控制器中切换或启用该参数。

为了获得更好的编码体验并避免重复,您可以使用一个类别存储库,而不是两个不同的控制器来处理桌面/移动路由

CategoriesRepository.php

class CategoriesRepository{

  public function update($category_id, $data = []){

     $category = Category::findOrFail($category_id);

     return $category->update($data);

  }

  //another category related methods
}
routes/web.php

Route::group(function(){
    Route::patch("category/{id}", 'CategoriesController@update');
});

//this can also be in the routes/api.php and will get the api prefix automatically
Route::group(["prefix" => "mobile"], function(){
    Route::patch("category/{id}", 'ApiCategoriesController@update');
});
CategoriesController.php

public function update(Request $request){
  (new CategoriesRepository)->update($request->category_id, $request->only("name", "type"));

  return view("categories.main");
}
public function update(Request $request){
  (new CategoriesRepository)->update($request->category_id, $request->only("name", "type"));

  return response([
    "success" => true,
    "message" => "The category has been updated successfully"
  ], 200);
}
ApiCategoriesController.php

public function update(Request $request){
  (new CategoriesRepository)->update($request->category_id, $request->only("name", "type"));

  return view("categories.main");
}
public function update(Request $request){
  (new CategoriesRepository)->update($request->category_id, $request->only("name", "type"));

  return response([
    "success" => true,
    "message" => "The category has been updated successfully"
  ], 200);
}

我将把函数隔离在另一个类中,类似于
(newcategoriesrepo)->update($cat_id)然后您可以设置不同的路由来处理此问题,一个用于桌面版本,一个用于API,在此函数中对此类执行相同的调用,并且对于每个路由,成功后都有不同的响应。在桌面上执行返回视图('some.view')
,在手机上执行返回响应()->json([“success”=>true],200)@AfikDeri感谢您的评论,您能否提供更多详细信息作为示例回答