O. Shekriladze
O. Shekriladze

Reputation: 1536

Can't call parent function inside __call() in Laravel

This is my code below.

class MyModel extends Model
{
    public function __call($method, $parameters = null) {
        if($method == 'create'){
            return parent::create($parameters[0]);
            if(!$created) {
                throw new \App\Exceptions\EloquentException;
            }else{
                return $created;
            }
        }
    }
}

The problem is that when I call update function of MyModel class instance from postman, something bad happens. It gets stuck and I have to restart my computer each time. So what may the problem be?

Upvotes: 1

Views: 428

Answers (1)

Sergey Telshevsky
Sergey Telshevsky

Reputation: 12197

I'll try to assume you're simply trying to have a common handler for the create function, that is, to throw an EloquentException in case the create returns a null or false.

If that's the case, you have an excess return statement on line above the if statement, and you should assign the return value of the parent's create method to a variable $created that you use later. You may also remove the else part as code below throw is never going to be executed if the exception is thrown.

class MyModel extends Model
{
    public function __call($method, $parameters = null)
    {
        if ($method == 'create') {
            $create = parent::create($parameters[0]);
            if (!$created) {
                throw new \App\Exceptions\EloquentException;
            }
            return $created;
        }
    }
}

It would be better if you could elaborate on the task you're trying to achieve, I feel you're doing it the wrong way.

Upvotes: 2

Related Questions