Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in observe function of HasEvent trait due to model dependency handling in Laravel 10.44.0 #50295

Closed
matin-kh73 opened this issue Feb 28, 2024 · 1 comment

Comments

@matin-kh73
Copy link

Laravel Version

10.44.0

PHP Version

8.1.4

Database Driver & Version

No response

Description

In version 10.44.0, we introduced a new feature called Introduce Observe attribute for models to facilitate the retrieval of model observers.

Within the HasEvents trait, there exists a method named bootHasEvents() which retrieves attributes from the model classes and subsequently passes them to the observe() method.

Consider a scenario where a model class (e.g., Post) has dependencies such as User, Comment, etc. When the observe method is invoked, we pass the class name to it, and then we create a new instance of that class using new static.
However, in cases where there is a dependency on a model class, an error is encountered, similar to the following:

Too few arguments to function App\Models\Post::__construct(), 0 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php on line 67 and at least 3 expected"

This error arises due to the expectation of constructor arguments not being met, causing issues when attempting to instantiate the model class by new static.

Steps To Reproduce

  1. Check the value of resolveObserveAttributes() and if attributes exist, then call the observe method.
  2. Instead of using new static, create a new instance of models using app(static::class) to properly handle the dependencies. This ensures that the IoC container resolves any dependencies automatically.
    public static function bootHasEvents(): void
    {
        if (!empty($attributes = static::resolveObserveAttributes())) {
            static::observe($attributes);
        }
    }
    public static function observe($classes)
    {
        $instance = app(static::class);

        foreach (Arr::wrap($classes) as $class) {
            $instance->registerObserver($class);
        }
    }
@crynobone
Copy link
Member

See #50284 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants