I'm trying to use redis as a default broadcaster in laravel here is my .env fille
QUEUE_DRIVER=sync
APP_ENV=local
APP_DEBUG=true
APP_KEY=***********
DB_HOST=***************
DB_PORT=******************
DB_DATABASE=***************
DB_USERNAME=***********
DB_PASSWORD=*************
CACHE_DRIVER=file
SESSION_DRIVER=file
BROADCAST_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
I'm using this event class to broadcast
<?php
namespace App\Events;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
use Log ;
class SomeEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
public $data;
public function __construct($room, $data)
{
Log::debug($room);
Log::debug($data);
$this->data = array(
'room' => $room,
'data' => $data
);
}
public function broadcastOn()
{
Log::debug('in channel!!!');
return ['test-channel'];
}
}
when i fire the event inside a controller using
event(new SomeEvent("test room", "test message"));
I get the following error
[2016-02-29 19:17:38] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Pusher' not found' in C:\xampp\htdocs\TechInsights\vendor\laravel\framework\src\Illuminate\Broadcasting\BroadcastManager.php:132
Stack trace:
The most strange thing is when i change the method createPusherDriver inside the BroadcastManager.php
from
protected function createPusherDriver(array $config)
{
return new PusherBroadcaster(
new Pusher($config['key'], $config['secret'], $config['app_id'], Arr::get($config, 'options', []))
);
}
to
protected function createPusherDriver(array $config)
{
return new RedisBroadcaster(
$this->app->make('redis'), Arr::get($config, 'connection')
);
}
the event broadcasts in redis without any issue ! any ideas ? Why laravel using pusher even if i configured it to use redis ? what i'm missing ?
Have you tried clearing your config cache?
php artisan config:clear
Related
When in Laravel 9 app logged user fill ContactUs form I need to send email to site support and show
notification in app for any logged support member. I make it with notification and pusher
In app/Notifications/ContactUsCreatedNotification.php :
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\User;
class ContactUsCreatedNotification extends Notification
{
public $title;
public $content_message;
public $authorUser;
public function __construct(string $title, string $content_message, User $authorUser)
{
$this->title = $title;
$this->content_message = $content_message;
$this->authorUser = $authorUser;
}
public function via($notifiable)
{
return ['mail', 'broadcast']; // I added broadcast here
}
public function toMail($notifiable)
{
return (new MailMessage)->markdown('mail.ContactUsCreatedNotification', [
'title' => $this->title,
'content_message' => $this->content_message,
'authorUser' => $this->authorUser
]);
}
public function toArray($notifiable)
{
return [
'title' => $this->title,
'content_message' => $this->content_message,
'authorUser' => $this->authorUser,
];
}
}
I got email on configured mailtrap but Debug console of my pusher app has no event : https://prnt.sc/L9nXEfup_3i-
in .env :
BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
FILESYSTEM_DISK=local
SESSION_DRIVER=database
SESSION_LIFETIME=120
PUSHER_APP_ID=NNNN
PUSHER_APP_KEY=XXXXX
PUSHER_APP_SECRET=XXXXX
PUSHER_APP_CLUSTER=eu
In resources/js/bootstrap.js :
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
// alert('resources/js/bootstrap.js')
console.log('process.env.MIX_PUSHER_APP_KEY::')
console.log(process.env.MIX_PUSHER_APP_KEY)
console.log('process.env.MIX_PUSHER_APP_CLUSTER::')
console.log(process.env.MIX_PUSHER_APP_CLUSTER)
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true
});
In the app I have
"laravel/framework": "^v9.6.0",
"predis/predis": "^1.1",
"pusher/pusher-php-server": "^7.0",
and
"laravel-echo": "^1.11.7",
Any ideas why notification event is not triggered ?
UPDATED BLOCK # 1:
in .env file I set parameters
QUEUE_CONNECTION=redis
I do :
foreach ($supportManagers as $nextSupportManager) {
if ($nextSupportManager->user) {
$ret = Notification::sendNow($nextSupportManager->user, new ContactUsCreatedNotification(
$request->title,
$request->content_message,
auth()->user()
));
}
}
Also I tried to add Queueable definition i app/Notifications/ContactUsCreatedNotification.php file:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\User;
class ContactUsCreatedNotification extends Notification implements ShouldQueue
{
use Queueable;
public $title;
public $content_message;
public $authorUser;
But I still get email in mailtrap and not events in pusher...
Thanks!
I'm developing a new Laravel application. When I'm using mail to send messages via contact form in my website, I'm getting the following error:
Process could not be started [The system cannot find the path specified. ]
I'm developing in my local environment but using my business mail to get messages.
My controller:
namespace App\Http\Controllers;
use App\SendMessage;
use App\Mail\SendEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Session;
class SendMessageController extends Controller
{
public function store(Request $request) {
$this->validate($request, [
"email" => "required|email",
"message" => "min:10",
"subject" => "min:3"
]);
$name = $request->name;
$email = $request->email;
$company = $request->company;
$subject = $request->subject;
$message = $request->message;
Mail::to("audit#auditors.uz")->send(new SendEmail($subject, $message));
Session::flash("success", "Your email was sent");
return back();
}
}
?>
My mailing function:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $sub;
public $mese;
public function __construct($subject, $message)
{
$this->sub = $subject;
$this->mes = $message;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$e_subject = $this->sub;
$e_message = $this->mes;
return $this->view('emails.contact', compact("e_message"))->subject($e_subject);
}
}
?>
My .env file:
MAIL_DRIVER=mail
MAIL_HOST=mail.auditors.uz
MAIL_PORT=465
MAIL_USERNAME=audit#auditors.uz
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls
I googled it a lot, but did not find the appropriate answer. If anybody of you can help me, I'll be really happy. Because I've been looking for a solution for a long time.
Your MAIL_DRIVER is set to mail, which does not exist by default. If you are using an SMTP mail server, you should use smtp as the driver.
Please make sure that your email provider supports port 465 and TLS encryption. Most of the providers support these automatically though.
Use MAIL_DRIVER="smtp"
Do not forget to Re-Serve or clear cache of Laravel
[ php artisan optimize:clear / php artisan config:clear / php artisan cache:clear ]
I made an API with Laravel and it is registering the data correctly
Now I'm trying to get this to trigger registration confirmation emails, however these are not going
I'm using Mailtrap for the tests
In .env I put like this:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=291ac7fdcf52bb
MAIL_PASSWORD=610b2e5e9782d3
No Http/Mail/DataManifestMail.php tenho:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class DataManifestMail extends Mailable
{
use Queueable, SerializesModels;
protected $inputs;
public function __construct($inputs)
{
$this->inputs = $inputs;
}
public function build()
{
return $this->view('mails.data');
}
}
In views/mails/data.blade.php I only have one warning message:
<h1>Test e-mail</h1>
Then in my Http/Controller/ManifestationController.php I put it like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Manifestation;
use App\Mail\DataManifestationMail;
use Mail;
class ManifestationController extends Controller
{
private $manifestation;
public function __construct(Manifestation $manifestation)
{
$this->manifestation = $manifestation;
}
public function store(Request $request)
{
$nr = Manifestation::max('nrmanifestation');
$this->manifestation->nrmanifestation = $nr + 1;
$this->manifestation->dspass = $request->dspass;
$this->manifestation->eeemail = $request->eeemail;
$this->manifestation->address = $request->address;
$this->manifestation->name = $request->name;
$this->manifestation->latitude = $request->latitude;
$this->manifestation->longitude = $request->longitude;
$this->manifestation->save();
Mail::to('vazag#c1oramn.com')->send(new DataManifestationMail());
return response()->json([
'result' =>
$this->manifestation->nrmanifestation
]);
}
}
I have reread the documentation and my code several times and have not found any errors
What can it be?
There might be multiple reasons:
configuration is cached (use php artisan config:cache)
you used invalid mailtrap data (you should have log in laravel.log file)
your server has somehow blocked 2525 port
Also looking at your code it seems you miss passing $input parameter to constructor. You have:
public function __construct($inputs)
but you run:
->send(new DataManifestationMail());
without passing any value
I try on the my localhost, it works
But if I try on the staging server, it does not works
My controller like this :
<?php
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderReceivedMail;
...
class PurchaseController
{
...
public function test() {
$order = $this->order_repository->find(416);
$user = $this->user_repository->find(1);
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
}
}
My mail like this :
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderReceivedMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $order;
public $store;
public function __construct($order, $store)
{
$this->order = $order;
$this->store = $store;
$this->subject('subject');
}
public function build()
{
$mail_company = explode(',',config('app.mail_company'));
// dd($mail_company, $this->order->number, $this->store->name, 'test');
return $this->view('vendor.notifications.mail.email-order',['number'=>$this->order->number, 'store_name' => $this->store->name])->bcc($mail_company);
}
}
I try add this :
dd($mail_company, $this->order->number, $this->store->name, 'test');
on the mail
If in my localhost, the result of dd show
But if in the staging server, the result of dd not show
Seems if the staging server, it does not run this statement :
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
How can I solve this problem?
open config/mail.php, .env files and set your email driver as mail as bellow,
'driver' => env('MAIL_DRIVER', 'mail'), //you must set it in env file too
then you can send emails like bellow, note that emails.admin.member, is the path to your email template, in the example code, laravel will look for a blade template in the path, resources\views\emails\admin\member.blade.php
Mail::queue('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});
or
Mail::send('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});
I'm currently developing my personal application that is about private servers (for example, Minecraft servers) and since querying the server takes some time, I decided to implement queued jobs. However, they are not working properly, and they run immediately when called even though they are delayed, causing a massive latency in a page request.
Here's my HomeController's index() which calls the job to update every server with a 30 seconds delay:
public function index()
{
$servers = Server::all();
foreach($servers as $server)
{
// Job Dispatch
$job = (new UpdateServer($server->id))->delay(30);
$this->dispatch($job);
}
return view('serverlist.index', compact('servers'));
}
The job class that updates the servers is the following:
class UpdateServer extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $id;
public function __construct($id)
{
$this->id = $id;
}
public function handle(){
$server = Server::findOrFail($this->id);
// Preparing the packet
$test = new RAGBuffer();
$test->addChar('255');
$test->addChar('1');
$test->addShort(1 | 8);
// Finding the server
$serverGame = new RAGServer($server->server_ip);
// Get server information
$status = $serverGame->sendPacket($test);
$server->onlinePlayers = $status->getOnline();
$server->peakPlayers = $status->getPeak();
$server->maxPlayers = $status->getMax();
if (!$server->save()) {
// Error occurred
}
}
}
Whenever the HomeController's index() is run, there's a massive delay in the page request. I followed the tutorial at Laravel's Official Webpage, and I tried to find answers, but I didn't find anything.
So, what am I doing wrong? Why isn't the job getting delayed 30 seconds and then doing this in background in my server?
Also: The handle() is doing what it is supposed to. It queries the server, sends packets, and updates my database with the correct information.
You have to set up the queue driver you want to use in your project's root dir's .env file.
By default, the queue driver is sync which does exactly what you are describing, executing queues immediately.
You can choose of some different queue drivers, such as beanstalked or redis (which would be my choice). There's an excellent freebie on laracasts.com about setting up a beanstalked queue.
To view all available queue driver options in Laravel, have a look here.
Here's a .env example
APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync // <-- Put the desired driver here
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
This was driving me crazy for ages before I realised that Laravel 5.7 renamed QUEUE_DRIVER to QUEUE_CONNECTION in the .env files
For someone who has made the changes from previous answers and still didn't work, check the default value of the queue file like this: dd(Config::get('queue.default'))
For me it didn't change until flushing the config cache:
php artisan config:clear
To test locally you could set the driver to
QUEUE_DRIVER=database
And run php artisan queue:table.
And then php artisan migrate, so you would get your queue saved into the database, so you visually could see what`s going on.
And to run your queues, simply run php artisan queue:listen ... and leave it running as you do with artisan serve.
If you are running on php artisan serve, restart this and run php artisan serve again. This worked for me after hours trying to wonder what it was.
:)
If you are running tests against the queue service through phpunit, make sure that
<env name="QUEUE_DRIVER" value="X"/>
in phpunit.xml doesn't override your desired queue driver.
Ensure that
'default' => env('QUEUE_DRIVER', 'database'),
in file config/queue.php
And
QUEUE_DRIVER=database
in the .env file to ensure the database driver is used.
It's because the delay function takes an absolute date in the future
UpdateServer::dispatch($server->id)->delay(now()->addSeconds(30))
In my case, I had to implement ShouldQueue and use the Queueable trait:
class CustomNotification extends Notification implements ShouldQueue{
use Queueable;
...
Even if you have configured everything properly this can still happen. We had this problem with Laravel 5.4 where we created a lot of jobs, some delayed, and added them to the queue via Queue:bulk($jobs). This call and also Queue::push($job) completely ignore the delay and cause the job to be processed immediately.
If you want your job to be put on the queue as you configured it you must call dispatch($job).
This is the complete steps to create user API and store its history in jobs table.
In Jobs class:
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\Repositories\Eloquent\ApiRepo as ApiRepo;
use Log;
use App\Models\User;
class UserProcess implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted and override the queue tries.
*
* #var int
*/
public $tries = 3;
/**
* Create a new job instance.
*
* #return void
*/
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
try {
// make api call
Log::info("inside handle".$this->user->id);
$apiRepo = new ApiRepo;
$response = $apiRepo->getUserDetails($this->user->id);
Log::info("Response".$response);
} catch (\Throwable $exception) {
if ($this->attempts() > 3) {
// hard fail after 3 attempts
throw $exception;
}
// requeue this job to be executes
// in 3 minutes (180 seconds) from now
$this->release(180);
return;
}
}
}
In Controller Class:
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use App\Models\User;
use App\Jobs\UserProcess;
use App\Models\UserHistory;
use Carbon\Carbon;
class UserController extends Controller
{
public function create(Request $request)
{
$rules = [
'first_name' => 'required|string|max:100',
'last_name' => 'required|string|max:100',
'email' => 'required|string|email|unique:users,email',
'phone_number' => 'required|string|max:10',
'address' => 'string',
'date_of_birth' => 'string|date_format:Y-m-d|before:today',
'is_vaccinated' => 'string|in:YES,NO',
'vaccine_name' => 'string|required_if:is_vaccinated,==,YES|in:COVAXIN,COVISHIELD'
];
$validator = Validator::make(array_map('trim', ($request->all())),$rules);
if($validator->fails()){
return response()->json($validator->errors());
}else{
$user = new User;
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->phone_number = $request->phone_number;
$user->address = $request->address;
$user->date_of_birth = $request->date_of_birth;
$user->is_vaccinated = $request->is_vaccinated;
$user->vaccine_name = $request->vaccine_name;
$user->save();
$token = $user->createToken('auth_token')->plainTextToken;
if($user->save()){
$job = (new UserProcess($user))->delay(Carbon::now()->addMinutes(1));
$this->dispatch($job);
return response()
->json(['data' => $user,'status' => '200','message' => 'User Added Successfully','access_token' => $token, 'token_type' => 'Bearer']);
}else{
return response()
->json(['data' => $user,'status' => '409','message' => 'Something went wrong!']);
}
}
}
}
In ApiRepo Class:
namespace App\Repositories\Eloquent;
use App\Repositories\ApiInterface;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserHistory;
use Log;
class ApiRepo implements ApiInterface {
public function getUserDetails($userid) {
Log::info('User ID - '.#$userid);
$user_history = new UserHistory();
$save_user = User::find($userid);
Log::info('User Json Data - '.#$save_user);
$user_history->user_id = $userid;
$user_history->first_name = $save_user->first_name;
$user_history->last_name = $save_user->last_name;
$user_history->email = $save_user->email ;
$user_history->phone_number = $save_user->phone_number;
$user_history->address = $save_user->address;
$user_history->date_of_birth = $save_user->date_of_birth;
$user_history->is_vaccinated = $save_user->is_vaccinated;
$user_history->vaccine_name = $save_user->vaccine_name;
$user_history->save();
if($user_history->save()){
Log::info('User history Saved!');
}
}
}