I want to do a real time chat, with websocket/pusher.
Installed laravel websockets by following the command: composer require beyondcode/laravel-websockets
Publish it by using: php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan migrate
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config" (I configure file config/websocket.php)
Installed laravel pusher: composer require pusher/pusher-php-server "~3.0"
Uncommented App\Providers\BroadcastServiceProvider::class in config/app.php
Created a ChatEvent event
Launched websockets server by: php artisan websockets:serve
Opened link http://localhost/jwtchat/public/laravel-websockets then connect and everything works fine
I run php artisan tinker:
event(new App\Events\ChatEvent('hello'))
It works very well, but when I try http://localhost/jwtchat/public/broadcasting/auth in postman, it gives me 403 Forbidden error.
in payload it return me:
socket_id: 726245173.481815034
channel_name: presence-chat
.env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=YYYYY
PUSHER_APP_SECRET=ZZZZ
PUSHER_APP_CLUSTER=eu
broadcasting.php
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http'
],
],
websockets.php
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'enable_client_messages' => false,
'enable_statistics' => true,
],
],
ChatEvent.php
class ChatEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $mesage;
/**
* 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('chat');
}
Related
I'm having troubles with dispatching events on my local Laravel configuration.
I'm trying to dispach it directly from the dashboard http://localhost:8000/laravel-websockets, but it always return Error sending event. Even if it is connecting to the dashboard.
My config looks:
.env file:
QUEUE_CONNECTION=database
QUEUE_DRIVER=sync
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=local
PUSHER_APP_KEY=local
PUSHER_APP_SECRET=local
PUSHER_APP_CLUSTER=mt1
PUSHER_PORT=6001
PUSHER_SCHEME=http
PUSHER_HOST=127.0.0.1
Configuration in boradcasting.php:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'host' => env('PUSHER_HOST', 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
Configuration in websockets.php:
'apps' => [ [
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'path' => env('PUSHER_APP_PATH'),
'capacity' => null,
'enable_client_messages' => false,
'enable_statistics' => true,
],
],
I did enable all providers, and still not dispatching even from the dashboard.
I tried to create event and dispatch from the controller, but still not working.
Any ideas what could cause it?
Edit: just noticed in dashboard a message like:
Channels current state is connected
I've been having this problem for days and I don't know how to solve it.
I have a job that I'm dispatching from my controller, but once I do php artisan queue:work nothing shows up in my console (not windows, not a Linux terminal emulator like Cmder)
My job:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\ProfessorSuscription;
use App\Models\ProfessorSuscriptionHistory;
use Carbon\Carbon;
class CheckSuscription implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct()
{
}
public function handle()
{
$suscription_history = new ProfessorSuscriptionHistory();
$suscription_history->user_id = 13;
$suscription_history->type = 'trimestral';
$suscription_history->pdf = 'test.pdf';
$suscription_history->ended_at = Carbon::now()->addMonth(3);
$suscription_history->save();
}
}
That is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Jobs\CheckSuscription;
class TestController extends Controller
{
public function index()
{
CheckSuscription::dispatchNow();
}
}
Note: when I execute my controller by route, it works perfectly and saves me in the database
My queue config:
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
After i do php artisan queue:work:
PD: I used commands php artisan queue:table, php artisan cache:clear and php artisan config:clear
PD2: Nothing appears too in my jobs or failed_jobs table.
PD3: Nothing appears in my laravel.log related to my Job.
How can i fix it? I've searched for days and can't find a solution. Thank you.
EDIT: config/queue.php file:
'default' => env('QUEUE_CONNECTION', 'sync'),
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
],
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
You should set QUEUE_CONNECTION=database in your env file or to change the config/queue.php default value to database. After that you should use CheckSuscription::dispatch(); instead.
I am using beyondcode/laravel-websockets package in my backend, and laravel-echo & pusher-js in frontend.
I want to send a private message to the user by websockets from my own server.
Backend
routes/channel.php
use Illuminate\Support\Facades\Broadcast;
use App\Models\User;
Broadcast::channel('users.{id}', function (User $user, Int $id) {
return (int) $user->id === (int) $id;
});
app/Events/NewPrivateMessage.php
...
class NewPrivateMessage implements ShouldBroadcast{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(Message $message){
$this->message = $message;
}
public $message;
public function broadcastOn(){
return new PrivateChannel('users.'.$this->message->user_id);
}
public function broadcastWith(){
return ['message' => $this->message];
}
}
config/broadcasting.php
...
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http'
],
],
...
],
Frontend
...
import Echo from 'laravel-echo';
window.SPY = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
wsHost: window.location.hostname,
wsPort: 6001,
disableStats: true,
auth: {
headers: {
Authorization: `${store.state.auth.token.token_type} ${store.state.auth.token.access_token}`
}
}
});
window.SPY.private(`users.${store.state.auth.user.id}`)
.listen('NewPrivateMessage', (e) => {
console.log(e);
});
But when I run code below in tinker, nothing happend, no logs, no console.log()
broadcast(new \App\Events\NewPrivateMessage(\App\Models\Message::first()));
I am sure I remove comments in config/app.php for BroadcastServiceProvider
App\Providers\BroadcastServiceProvider::class,
and the auth for broadcasting is successful
also, I am sure I already connected with websockets
How can I fix this? I am using laravel 7.0. Thanks a lot ☺
I have multiple pusher accounts for my multi tenant laravel app with this configuration:
'pusher_it' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_IT_KEY'),
'secret' => env('PUSHER_APP_IT_SECRET'),
'app_id' => env('PUSHER_APP_IT_ID'),
'options' => [
'cluster' => 'eu',
'useTLS' => true
],
],
'pusher_es' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_ES_KEY'),
'secret' => env('PUSHER_ES_ES_SECRET'),
'app_id' => env('PUSHER_ES_ES_ID'),
'options' => [
'cluster' => 'eu',
'useTLS' => true
],
],
'pusher_pt' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_PT_KEY'),
'secret' => env('PUSHER_APP_PT_SECRET'),
'app_id' => env('PUSHER_APP_PT_ID'),
'options' => [
'cluster' => 'eu',
'useTLS' => true
],
],
When I send a new notification:
Notification::send($usersToNotify, (new VehicleFailureEstimateNotification($vehicleFailureEstimate))->locale(App::getLocale()));
I would set on the fly the pusher configuration:
class VehicleFailureEstimateNotification extends Notification
{
use Queueable;
/**
* #var VehicleFailureEstimate
*/
private $vehicleFailureEstimate;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(VehicleFailureEstimate $vehicleFailureEstimate)
{
Broadcast::setDefaultDriver('pusher_'.$this->locale);
Broadcast::connection('pusher_'.$this->locale);
$this->vehicleFailureEstimate = $vehicleFailureEstimate;
}
But the notification is fired always through .env default BROADCAST_DRIVER=pusher_it
Can you help me? Thank you
It has been a long time question but I hope it will help someone.
It can be set config in your constructor in your case OR in BroadcastServiceProvider.php in boot method
config()->set('broadcasting.default', 'pusher_'.$this->locale);
I tested it and it works for me.
I am facing some issue with cron job in Yii2 application.
I am define Controller in console as follow
namespace console\controllers;
use yii\console\Controller;
/**
* Job controller
*/
class JobController extends Controller {
public function actionIndex() {
echo "cron service runnning";
mail("mail#gmail.com","Cron",'Testing');
}
}
Path in cpenal is
php /home/user/public_html/root/ yii job
I always receiving email with error
Status: 404 Not Found
X-Powered-By: PHP/5.5.38
Content-type: text/html
No input file specified.
I think there is issue with cmd supplied for it.
Please help me to sort out this issue.
Thankyou
1.show system crontab log
why you do not use yii\swiftmailer\Mailer
$components = [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.xxx.com',
'username' => 'xx#xxx.com',
'password' => 'xxx',
'port' => '25',
'encryption' => 'tls',
],
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['xx#xx.com' => 'contents']
],
]
];
Yii::$app->setComponents($components);
$mail= Yii::$app->mailer->compose();
$mail->setTo(['from#xxx.com', 'to#xx.com']);
$mail->setSubject($subject);
$mail->setHtmlBody($content);
$mail->send();