I have two routes in my Web.php,
Route::get('/employees', [ApiController::class, 'employees'])->name('employees');
Route::post('/employeesPost', [ApiController::class, 'employees'])->name('employees.post');
This is Controller Code, where I am fetching data from database, and sand it in JSON format:
public function employees() {
try {
//code...
$employees = Employees::all();
$data = [];
$usingCollection = new EmployeeCollection($employees);
// format data
foreach ($employees as $key => $employee) {
$data[] = [
'id' => $employee->id,
'name' => $employee->name,
];
}
// make response array
$response = [
'message' => 'successful get data',
'code' => 200,
'Employees' => $usingCollection,
];
return response()->json($response, 200);
} catch (\Throwable $th) {
$response = [
'message' => 'Something went Wrong',
'code' => 404,
'Employees' => $th->getMessage(),
];
return response()->json($response, 404);
}
}
My GET Route is working great, but I want to get same data using POST route, if anyone can help.
You can use same API in the
GetandPostmethod.This code handles both GET and POST requests to the /employees endpoint.