Can I get same data using POST rote that I got using GET route

40 Views Asked by At

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.

1

There are 1 best solutions below

2
Enjoy Coding. On

You can use same API in the Get and Post method.

Route::get('/employees', [ApiController::class, 'employees'])->name('employees');
Route::post('/employees', [ApiController::class, 'employees'])->name('employees.post');

This code handles both GET and POST requests to the /employees endpoint.