I got this error in my application, even though I already searched on Google but there is no question like this. It's weird. Error:
BadMethodCallException(code: 0): Call to undefined method App\\Http\\Models\\User::posts() at /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:5
This is my User.php
class User extends Model
{
...
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
PostListener.php
class PostListener implements ShouldQueue
{
public function handle(PostCreatedEvent $event)
{
$user = User::find($event->id);
$user->total_posts = $user->posts()->count();
}
}
This is my .env
BROADCAST_DRIVER=log
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_PREFIX=
CACHE_PREFIX=cache
As I mentioned above, it throws an exception. But after removing implements ShouldQueue
in PostListener.php
, it works well.
Anyone faced with this issue before, please help me
CodePudding user response:
Unless you have a really good reason, which doesn't seem you have, prefer eager loading instead of lazy loading. You can solve your problem like this:
$user = User::withCount('posts')->find($event->id);
CodePudding user response:
It was resolved already. I believed that it should be Redis issue since I tried other drivers of queue, and it worked. After trying to restart worker, it worked well for me. Thanks all. This is my script:
php artisan queue:restart