Let's assume I have a Laravel application where I have a page where I display all my customers in a table. So in my web.php
I point /customers
to the index
method in my CustomersController
. The index
method gets all the customer objects and returns them and the index blade in a view.
Now I also would like to build an api using the api.php
routes where I can get all my customers with a request. But if I point /customers
to the index
method in my api.php
routes it would return a view and not all the customer objects. Which would be useless.
So my question is what the best way and most efficient way is to handle this problem. Because creating a "duplicate" CustomerController just for the api requests seems a little too excesive.
CodePudding user response:
you can add a condition in the index method
for example:
public function index(Request $request){
if($request->is("api*"){
return response($customers);
}
$data['customers'] = $customers;
return view("customers blade")->with($data);
}