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?

\$\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.

\$\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.

\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.