简体   繁体   中英

Function return doesnt call else condition in Laravel 5.8

I have this big function that is calling a lot of other functions who that make API requests to BlackBoard, my problem is, in this main function, I create my user and sign him to the current course, but actually we faced this situation: that same user is already registered in BlackBoard, so I made an update function, to that specific case. But that main function it's all in a try catch block, so every time that I call the method:

$userSalvo = $bd->createUser($user)

and the user already exist in BlackBoard database, he immediatly stop my function and call the catch block, to obviously get the exception, but I need if that user already exist, he comeback from this request and go to the next method:

$userSalvo = $bd->updateUser($user, $userId);

I already tried to put this in a if statement, but It doesnt work as it should:

                    if($userSalvo = $bd->createUser($user))
                    {
                        dd('create');
                        $user->id = $userSalvo['id'];
                    }else
                    {
                        dd('update');
                        $userSalvo = $bd->updateUser($user, $userId);
                        $user->id = $userSalvo['id'];
                    }

Anyone has some ideia of how can I do this?

This is the API method that I'm calling to update/create:

     public function updateUser($user, $userId)
    {
        $user->dataSourceId = $this->dataSourceId;
        return $this->bd->patch("/users/{$userId}", json_decode(json_encode($user), true));
    }
    
    public function createUser($user)
    {
        $user->dataSourceId = $this->dataSourceId;
        return $this->bd->post("/users", json_decode(json_encode($user), true));
    }

You should then use the try-catch block if you do not want to refactor your code. What's happening by the sounds of it is your if condition dies as 'createUser' is called.

Rather try this to replace your entire if statement.

try{
    $userSalvo = $bd->createUser($user)
}catch(Exception $e){
    $userSalvo = $bd->updateUser($user, $userId);
}

This is assuming that $user and $userId is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM