Laravel 5.5 - SerializesModels on an event causes a ModelIdentifier error?

I have a laravel event with multiple listeners. Some listeners or their notifications (depending on how much time they take) implement ShouldQueue, so they run in the background in a queue redis. The event uses SerializesModelsby default, but when one of the transmitted models for the event is a registered user, and we fire it, for example:

$user = $this->user(); // logged in user instance
event(new UserCreatedPost($user, $post, $modelX, $modelY));

I cannot access user subscribers in the appropriate listener to check if they should be notified if they exist:

// In listener handle method
public function handle(UserCreatedPost $event){
    $followers = $event->user->followers()->get();
}

I get this error:

Call to undefined method Illuminate\Contracts\Database\ModelIdentifier::followers()

The only way I was able to get it to work was to add an event trigger below:

public function handle(UserCreatedPost $event){
    // This fixes it, as it unserializes all the models
    // (even though we only need this model to be unserialized, not all of them)
    $event->__wakeup();


    $followers = $event->user->followers()->first();
    // If at least one follower exists send queued notification
    // else exit
}

I do $user . , $user , , SerializesModels ( , ).

$user wakeup? , , wakeup , , . SerializesModels , , . - , , , , , , ? ?

+4
1

__wakeup() ( SerializesModels) , . , ( ) . , , . .

, , . , , ( , Model::find($id), ?).

$user = $this->user(); // logged in user instance
event(new UserCreatedPost($user->id, $post->id, $modelX->id, $modelY->id));

:

// In listener handle method
public function handle(UserCreatedPost $event){
    $user = User::find($event->user);
    $followers = $user->followers()->get();

    // the other stuff you want to do...
}

, , .. , , , - . - , , , CallQueuedListener.

, Laravel , : , , . , .

+1

Source: https://habr.com/ru/post/1695590/


All Articles