0

I have this Model UserSetting.php:

class UserSetting extends Model
{
    protected $fillable = ['user_id', 'name', 'setting_value'];

    public static function set($user_id, $name, $value)
    {

        if (!User::find($user_id)) {
            return error('NoForeign_User');
        }

        self::updateOrCreate(
            ['user_id' => $user_id, 'name' => $name],
            ['setting_value' => $value]
        );
    }
}

And I want to use it this way inside UserSettingController.php:

public function user(Request $request)
{
    Validator::make($request->all(), [
        'user_id'       => 'required|int',
        'name'          => 'required|string',
        'setting_value' => 'required|string',
    ], $this->messages)->validate();

    // HERE IS THE CALL
    UserSetting::set($request->user_id, $request->name, $request->setting_value);

    return saved();
}

I need to call UserSetting statically but NOT with a return:

return UserSetting::set(...)

But when the static function gets to the if(!User::find($user_id)) it carries on and shows the saved() helper instead of the return error('NoForeign_User')

While if I do it with a return return UserSetting::set(...) it correctly shows the error.

Is this correct? Do I have any other option other then returning the static class?

EDIT:

My error() function is this:

function error($message, $code = 422)
{
    $response = ['message' => $message];
    if ($errors) {
        $response += [
            'errors' => $errors,
        ];
    }

    return response()->json([
        'message' => $message,
    ], $code);
}

1 Answer 1

1

If you don't check the result that is being returned when calling the static method, then for sure the program will continue to execute the next line which is the saved() method in your case.

In order to stop execution a better approach is to throw an exception which will propagate to the Exception handler and stop the function execution.

So instead of this:

if (!User::find($user_id)) {
    return error('NoForeign_User');
}

try this:

if (!User::find($user_id)) {
    throw new \Exception('NoForeign_User');
}

or yet another and the best approach in my opinion that I just remembered is to simply use the findOrFail function:

User::findOrFail($user_id);

This will also throw an exception if the user has not been found.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.