Problem
Question is quite simple, I am using dingo
package, Currently below is my code for an API call.
public function publishApplicant(Request $request,$id){
$changeStatus = AppUser::where('id', $id)->update(array('admin_published' => 1));
if($changeStatus){
return response()->json([
'message' => 'Applicant published.',
'code' => 200,
'status' => 1
], 200);
}
return response()->json([
'message' => 'Applicant published.',
'code' => 500,
'status' => 0
], 200);
}
What can be improved in the above code?
Solution
Not a big improvement, but since $changeStatus
is responsible for a different 'code'
and 'status'
and the rest is identical, we may do something like the following:
public function publishApplicant(Request $request,$id)
{
$changeStatus = AppUser::where('id', $id)->update([
'admin_published' => 1
]);
return response()->json([
'code' => $changeStatus ? 200 : 500,
'message' => 'Applicant published.',
'status' => $changeStatus ? 1 : 0
], 200);
}
I’ve also applied some PSR-2 coding style adaptments, nothing too fancy but it makes it a bit more readable.
Anyway you may want to change the message in case of failure.
You could store the response in a variable and only call return once. That seems cleaner. Also, put constants like messages and HTTP codes into constant variables.