Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kendrick's avatar

Argument 2 passed must be of the type int, string given

Within User.php I have a friends() relationship:

public function friends(){
    return $this->belongsToMany(User::class, 'friends', 'user_id', 'friend_id')->withTimestamps(); 
}

Now, whenever a friend makes a Post.php, I would like to broadcast this Post only to friends

Currently I am checking on a Channel which has {postId} in it, and it don't works. It returns Posts.undefined, as I am listening to the Channel as a logged-in user, but a postId is logically not available.

Broadcast::channel('Posts.{postId}', function (User $user, int $postId) {
    $post = Post::findOrFail($postId);
    return $user->friends()->where('friend_id', $post->user_id)->exists();
});

Argument 2 passed to App\Providers\BroadcastServiceProvider::{closure}() must be of the type int, string given, called in App\Providers\BroadcastServiceProvider->{closure}(Object(App\Models\User), 'undefined')

Is there another way, to broadcast only friend related Posts?

Would it be possible if I check on userId within the Channel, and then check if the userId (authenticated user), counts a friend which made that Post?

0 likes
2 replies
bobbybouwmann's avatar

Why don't you just broadcast to the user id instead of the post id?

Broadcast::channel('Users.{userId}', function (User $user, int $userId) {
    return $user->friends()->where('friend_id', $userId)->exists();
});
1 like
kendrick's avatar

@bobbybouwmann How would I then get the userId from my friend? Because currently within my component, I pass the authenticated user as a prop, who basically waits to receive the Post, but isn't referenced within the Post model which should be broadcasted? Or am I thinking too complicated here?

This is the current setup:

<template>
    <div>      
      <div v-for="post in posts">   
          <post :post="post"></post> 
      </div>    
    </div>
</template>

<script>

export default { 

    props: ['user'],

    data() {
        return {
            posts: [],   
        }
    },
    
    created() { 
    
        Echo.private(`Posts.${this.post.id}`)
        .listen('PostCreated', (e) => {
            this.fetchPosts();
        });

     },

     methods: {
       fetchPosts(){
           axios.get('/api/posts/' + this.user.id).then(response => this.posts = response.data.data);
       }
    }  


};
</script>

PostController

$post = Auth::user()->posts()->create([
      'user_id' => auth()->user()->id,
      'body' => $request->body,   
]);

broadcast(new PostCreated($post));

With:

Broadcast::channel('Users.{userId}', function (User $user, int $userId) {
    return $user->friends()->where('friend_id', $userId)->exists();
});

I would need to pass $user to the Event?

Please or to participate in this conversation.