I have Laravel 6 and use pusher as a broadcast event. But I get this error (see screenshot)
the error
\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php:121
screenshot stacktrace error
here is my controller:
public function sendMessage(Request $request)
{
//validate incoming request
$this->validate($request, [
'message' => 'required|string'
]);
try {
$iam = Auth::user();
$message = $iam->family->messages()->create([
'message' => $request->input('message'),
'id_user' => $iam->id
]);
event(new ChatSubmitted('$message'));
//return successful response
return response()->json(['messages' => $request->all(), 'message' => 'Send Message Succesfully'], 200);
} catch (\Exception $e) {dd($e);
//return error message
return response()->json(['message' => 'Send Message Failed!'], 409);
}
}
and here is my event:
class ChatSubmitted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('my-channel');
}
}
the routes of api:
Route::get('messages', 'ChatsController#fetchMessages');
Route::post('messages/create', 'ChatsController#sendMessage');
Related
i am creating A notifcation for user that created a new post on my site and the user will be awarded point after creating a post, so when a user create a post and get a point send notification but im getting this error
👉 Property [id] does not exist on this collection instance.
please how can I resolve this issue kindly assist me
<?php
namespace App\Http\Livewire;
use App\Gamify\Points\PostCreated;
use App\Models\Category;
use App\Models\Post;
use App\Models\Tag;
use App\Models\User;
use App\Notifications\PointAdd;
use Illuminate\Support\Str;
use Livewire\Component;
use Illuminate\Http\Response;
use Livewire\WithFileUploads;
class PostCreate extends Component
{
use WithFileUploads;
public $post;
public $user;
public $body;
public $slug;
public $photo;
public $title;
public $category = 1;
public $points = 10;
public $energy = 1;
public function increment()
{
$this->points++;
}
protected $rules = [
'category' => 'required|integer|exists:categories,id',
'title' => 'required|min:4',
'body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$random = str_pad(mt_rand(1,999999),6,'0',STR_PAD_LEFT);
$post = Post::create([
'user_id' => auth()->user()->id,
'title' => $this->title,
'category_id' => $this->category,
'body' => $this->body,
'post_number' => $random,
'slug' => Str::slug($this->title),
]);
$user = auth()->user();
$points = $user->givePoint(new PostCreated($post));
$user->notify(new PointAdd($points));
$image = $this->photo->storeAs('posts', str::random(30));
$post->image = $image;
$post->save();
session()->flash("message", "Featured image successfully uploaded");
preg_match_all('/(?<=#)(\w+)/mi', $this->body, $matchedTags, PREG_SET_ORDER, 0);
foreach ($matchedTags as $matchedTag) {
if (!$tag = Tag::where('name', $matchedTag[0])->first()) {
$tag = tag::create(['name' => $matchedTag[0]]);
}
$post->tags()->attach($tag->id);
$tag->addEnergy(1);
}
preg_match_all('/(?<=#)(\w+)/mi', $this->body, $matchedMentions, PREG_SET_ORDER, 0);
foreach ($matchedMentions as $matchedMention) {
optional(User::where('username', $matchedMention[0])->first(), function ($user) {
// $user->notify(new MentionsNotify($user));
});
}
// $users = auth()->user();
// $users->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('post.index');
}
abort(Response::HTTP_FORBIDDEN);
}
}
My notification components
<?php
namespace App\Notifications;
use App\Models\Post;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class PointAdd extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'user_id' => $this->user->id,
'user_name' => $this->user->name,
'user_avatar' => $this->user->avatar,
'user_points' => $this->user->reputation,
'post_id' => $this->user->post->id,
];
}
}
You are passing a $points object to notification which expects a User model. If your givePoint() method (which you didn't share) does not return a User model then that's the problem.
You can add in your notification, under use Queueable; the protected User $user; definition and check if notification throws an error.
Show the Notification when the data is stored in the database, but when I want to create the Notification. This error occurs
use Queueable;
public $user;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($user)
{
$this->user = $user;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'name' => $this->user->name,
'email' => $this->user->email,
];
}
Pusher did not receive any data from my laravel project. in the debug console still waiting for events
and i didn't get any error message
My Controller
public function store(Request $request){
$user = Auth::user();
$message = $user->messages()->create([
'message' => $request->message,
'room_id' => $request->room_id
]);
broadcast(new MessageSent(auth()->user(), $message))->toOthers();
return response()->json([
'success' => true,
'message' => 'Chat Has Been Added',
], 200);
}
My Event
public function __construct(User $user, GrupChat $grupchat)
{
$this->user = $user;
$this->grupchat = $grupchat;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('chat');
}
}
And The channels.php
Broadcast::channel('chat', function ($user) {
return Auth::check();
});
I followed this tutorial to set up a messenger on my laravel application. My laravel logs show the type of messages below, which tells me that messages are being broadcast, but I'm not seeing them show up on Pusher! I've checked and double checked my pusher credentials and cluster and they are right.
[2020-06-06 14:49:30] local.INFO: Broadcasting [message.posted] on channels [private-
conversation.1] with payload:
{
"message": {
"id": 17,
"content": "h",
"sender_id": 1,
"conversation_id": "1",
"created_at": "2020-06-06T14:49:30.000000Z",
"updated_at": "2020-06-06T14:49:30.000000Z",
"conversation": {
"id": 1,
"new_messages": 0,
"created_at": "2020-06-06T15:41:25.000000Z",
"updated_at": "2020-06-06T14:49:30.000000Z"
}
},
"socket": null
}
I've created an endpoint to send messages and I'm triggering it with Postman. Below are my controller and the event that I'm triggering that should be broadcasting to pusher:
Store method in my controller:
public function store($id, Request $request)
{
$sender_id = auth()->user()->id;
$conversation = Conversation::find($id);
$content = $request->content;
// check that user belongs to the conversation
// updated conversation updated_at
// save message
if (in_array($sender_id, $conversation->users->pluck('id')->toArray())) {
// if the user is a participant in the conversation, they can save message
$message = Message::create([
'sender_id' => $sender_id,
'content' => $content,
'conversation_id' => $id
]);
// update the conversation updated_at
$conversation->touch();
} else {
// if user is not a participant in the conversation
return response([
'message' => 'Sorry, you are not part of this conversation and cannot post messages here'
]);
}
// fire new message posted event
event(new MessageWasPosted($message));
return response([
'message' => 'Message successfully posted',
'content' => $content
]);
}
My event:
class MessageWasPosted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* The message
*
* #var mixed
*/
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('conversation.'.$this->message->conversation->id);
}
/**
* The event's broadcast name
*
* #return string
*
*/
public function broadcastAs()
{
return 'message.posted';
}
}
To make sure auth is not an issue, I just return true in a Channel that I'm using:
<?php
namespace App\Broadcasting;
use App\User;
use App\Conversation;
class ConversationChannel
{
public function __construct()
{
}
/**
* Authenticate the user's access to the channel.
*
* #param \App\User $user
* #return array|bool
*/
public function join(User $user, Conversation $conversation)
{
return true;
return $conversation->users->contains($user);
}
}
On the Pusher debug console I see nothing coming through... Eventhough every now and then I see a random connection happening, no messages are being sent. Is there something obvious I'm missing?
PS: I've tried public channels, and they don't work either.
error
enter image description here
I am trying to send notifications of the event when some likes and comment on his post, notifications for comments and likes working
here is my notification class.
i have error in my CommentController if ($event->user_id != $comment->user_id)
class NewCommentEvent extends Notification
{
use Queueable;
protected $comment;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment = $comment;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'comment' => $this->comment,
'event' => Event::find($this->comment->event_id),
'user' => User::find($this->comment->user_id)
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
My controller function code for notifications on comments
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}
my CommenRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class CommentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'comment' => 'required|max:2000',
];
}
}
In your controller: the variable $comment is not defined.
From Laravel docs:
The create method returns the saved model instance.
so the solution is:
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
you have not defined your $comment, you just created a comment. This is throwing the error
$comment = Comment::create([
.
.
]);
This will fix your issue
The error message was clear. $comment is undefined. Replace your controller code with the follow:
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
// defined comment here
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}