2
\$\begingroup\$

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 = \App\User::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?

alecxe
17.5k8 gold badges52 silver badges93 bronze badges
asked Sep 9, 2017 at 14:44
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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 = \App\User::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.

answered Sep 10, 2017 at 8:10
\$\endgroup\$
0
1
\$\begingroup\$

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.

answered Sep 9, 2017 at 18:43
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.