当你有一个 API 和一个网站时如何设置路由
How to setup routes when you have an API and a website
假设我有一个 Laravel 应用程序,其中有一个页面,我在 table 中显示我的所有客户。所以在我的 web.php
中,我将 /customers
指向 CustomersController
中的 index
方法。 index
方法获取所有客户 objects 和 return 以及视图中的索引 blade。
现在我还想使用 api.php
路由构建一个 api,我可以让所有客户收到请求。但是,如果我将 /customers
指向 api.php
路由中的 index
方法,它将 return 一个视图而不是所有客户 objects。哪个没用。
所以我的问题是处理这个问题的最好方法和最有效的方法是什么。因为只为 api 请求创建一个“重复的”CustomerController 似乎有点过分了。
可以在索引方法中添加条件
例如:
public function index(Request $request){
if($request->is("api*"){
return response($customers);
}
$data['customers'] = $customers;
return view("customers blade")->with($data);
}
假设我有一个 Laravel 应用程序,其中有一个页面,我在 table 中显示我的所有客户。所以在我的 web.php
中,我将 /customers
指向 CustomersController
中的 index
方法。 index
方法获取所有客户 objects 和 return 以及视图中的索引 blade。
现在我还想使用 api.php
路由构建一个 api,我可以让所有客户收到请求。但是,如果我将 /customers
指向 api.php
路由中的 index
方法,它将 return 一个视图而不是所有客户 objects。哪个没用。
所以我的问题是处理这个问题的最好方法和最有效的方法是什么。因为只为 api 请求创建一个“重复的”CustomerController 似乎有点过分了。
可以在索引方法中添加条件
例如:
public function index(Request $request){
if($request->is("api*"){
return response($customers);
}
$data['customers'] = $customers;
return view("customers blade")->with($data);
}