2
\$\begingroup\$

I'm working on creating code with a nice balance between concise and readable. How would you improve this Laravel code block to make it more compact and readable?

    public function canEdit(Request $request)
    {
        $canEdit = Permission::canEdit(
            $request->user(), 
            $request->siteModel
        );

        $statusCode = ($canEdit) ? 200 : 403;

        return Response()
            ->json([
                'can-edit' => $canEdit
            ], $statusCode);
    }

Really looking forward for some comments / suggestions.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I don't see much to review here. Outside of declaring $payload['can-edit'] = ... and removing the parentheses from $statusCode, I don't think there is anything to change. I mean, even $payload['can-edit'] is a subject decision to declutter the ->json() parameters -- which I probably wouldn't do personally. \$\endgroup\$ Commented Sep 24, 2021 at 8:43

1 Answer 1

3
\$\begingroup\$

I agree with mickmackusa that your code is pretty good overall. If you wanted to condense it, you can refactor to something like below:

public function canEdit(Request $request) {
  $canEdit = Permission::canEdit($request->user(), $request->siteModel);

  return response()->json(['can-edit' => $canEdit], $canEdit ? 200 : 403);
}
  • Placing the opening brace on the same line as your canEdit() definition can help condense, but if you use a newline, keep it consistent
  • Both the $canEdit = ...; definition and return response()->json(..); statements are under the recommended 80 characters line length, so removing the line breaks is fine
  • The definition of $statusCode can be removed in favour of an in-line ternary as the 2nd parameter to your json() method, as defining a variable for a single use is unnecessary
  • You can add or remove a line-break between your two statements, I prefer an empty line before return, but depends on your configuration/consistency
\$\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.