I'm creating a command for sending an email automatically daily.
I'm creating the command like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class SendEmail extends Command
{
protected $signature = 'emails:send';
protected $description = 'Sending emails to the users.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$data = array(
'name' => "МГ 'Константин Величков', гр. Пазарджик",
);
Mail::send('emails.test', $data, function ($message) {
$message->from('mg.kvelichkov#gmail.com', 'МГ "Константин Величков"');
$message->to('yoannam1502#gmail.com')->subject('Оценки');
});
$this->info('The emails are send successfully!');
}
}
And then register it in Kernel like this:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Commands\Inspire::class,
Commands\SendEmail::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:send')->daily();
}
}
I'm listing all artisan commands and i can see my new comand emails:send - therefore its created, but when i try to run it (php artisan emails:send) i got this:
[Swift_TransportException] Process could not be started [The system
cannot find the path specified. ]
What is the problem?
It seems Gmail is blocking sending emails or your environment blocks connection.
Go to this address to unlock your Gmail account. Also, check firewall settings on your server.
Related
in db i have column visit_clear i want it 0 after one day so i used this code
in kernal.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
];
protected function schedule(Schedule $schedule)
{
$schedule->command('cron:update-user-not-new')->daily();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
and in command/UpdateUserNotNew.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateUserNotNew extends Command
{
protected $signature = 'cron:update-user-not-new';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$dayAgo = 1; // Days ago
$dayToCheck = \Carbon\Carbon::now()->subDays($dayAgo)->format('Y-m-d');
Customer::whereDate('visit_date', '<=', $dayToCheck)
->update([
'visit_clear' => 0
]);
}
}
i am sheduling commnd like this as u can see cron:update-user-not-new should i use crone:UpdateUserNotNew?
You need to register your command in Kernel.php like this:
protected $commands = [
'App\Console\Commands\UpdateUserNotNew',
];
You should then be able to run the command manually with php artisan cron:update-user-not-new
In order for the automatic running of the command to work, you need to add an entry to your system's task scheduler, as this is what Laravel uses to run commands on a schedule.
Assuming you are using Linux, you need to add an entry to your crontab. To do this, in a command prompt enter crontab -e, hit enter, and add this line:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Don't forget to replace /path-to-your-project with the root folder of your project
Once done editing the crontab, save and close the editor and the new entries should be installed, and your command should now run on the schedule.
All this info came from https://laravel.com/docs/7.x/scheduling so if you need more info take a look there
So I am trying to implement a command that notifies all users that are subscribes to an event with command that does an check every day. I was reading Laravel mail docs 7.x so there example is about order system where they send the mail with this peace of code
foreach (['taylor#example.com', 'dries#example.com'] as $recipient) {
Mail::to($recipient)->send(new OrderShipped($order));
}
what as it looks takes the email of of the loop and then send an email toward that adress.
So I made a mail class php artisan make:mail NotifyUserOfEvents
and where I made this code
<?php
namespace App\Mail;
use App\Event;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class NotifyUserOfEvents extends Mailable
{
use Queueable, SerializesModels;
protected $event;
public function __construct(Event $event)
{
$this->event = $event;
}
public function build()
{
return $this->view('mails.NotifyUserOfEvents')
->with([
'name' => $this->event->name,
'date' => $this->event->settings->start_date,
]);
}
}
but when I try to call this class with this function
<?php
namespace App\Console\Commands;
use App\Event;
use App\RegistrationEvents;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class NotifyUsersForEvents extends Command
{
protected $signature = 'NotifyUsersForEvents';
protected $description = 'Notify the user for the event. test run with -> php artisan schedule:run';
public function __construct()
{
parent::__construct();
}
public function handle()
{
Log::debug('this works every minute');
$events = Event::query()
->with('settings')
->has('settings')
->get();
foreach ($events as $event) {
$week = Carbon::now()->addWeek();
$sixDays = $week->copy()->subDay();
if (Carbon::create($event->settings->date_start)->between($week, $sixDays)) {
$subscriptions = RegistrationEvents::query()
->where('event_id', $event->id)
->get();
foreach ($subscriptions as $subscription) {
var_dump($subscription->user_id);
$user = User::findOrFail($subscription->user_id);
Mail::to($user->email)->send($event);
var_dump($user->email);
}
}
}
}
}
it returns this error: Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given, called in so do I need to change the way I call the mail class or do I need to add something to the Event Model?
also the event.php
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Event extends Model implements Mailable
{
use SoftDeletes;
public function settings(){
return $this->hasOne('App\EventSettings', 'event_id');
}
}
You must pass to send function an object of your NotifyUserOfEvents, not an Event object.
Try this:
Mail::to($user->email)->send(new NotifyUserOfEvents($event));
Referring to this line:
Mail::to($user->email)->send(new Event($event));
you are creating a new Event passing to the constructor another Event... you probably never define a constructor that accept as first parameter an Event...
But despite that, what's the sense of doing this? To Mail::send you have to pass a Mailable, not an event, and i'm pretty sure you don't need a new event, so i believe you would want to do something like this:
use App\Mail\NotifyUserOfEvents; // or whatever namespace you have to the mail
Mail::to($user->email)->send(new NotifyUserOfEvents($event));
$user = User::find($id);
$email = $user->email;
if(Helper::isValidEmail($email))
{
Mail::send('emails.applicant_reference',
$emailParameters, function($message) use ($email, $name, $subject){
$message->to($email, $name)
->subject($subject);
});
$applicantName = null;
$subject = " Application received for ".$applicantName;
$emailParameters = ["applicantName" => $applicantName, "proposerName" => $proposerName, "seconderName" => $seconderName];
try
{
Mail::send('emails.application', $emailParameters, function($message) use ($applicantName, $subject){
$message->to(['test#gmail.com','test#gamil.com'], " Test Email Function ")
->subject($subject);
});
} catch (Exception $ex){ Log::error("UserController".$ex->getMessage());
}
I have a problem when I use
php artisan schedule:run
And that command returns
No scheduled commands are ready to run.
My server allows to call CRON above each 5 minutes.
So I think my server setting is the reason not to work schedule:run.
So I need to try CRON without Task Scheduler, and check if the CRON return correct response or not.
So please tell me how can I use CRON without Task Scheduler.
As information, I put my codes below.
These codes work correctly to send E-mail and make log when I use
php artisan command:notice_expired_date
Kernel.php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
'\App\Console\Commands\NoticeExpiredDateCommand',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('command:notice_expired_date')
->daily()
->at(config('const.OPEN_TIME.FROM'))
->appendOutputTo(storage_path('logs/schedule/notice_expired_date.log'));
}
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
ExpiredDateNotification.php
namespace App\Console\Commands;
use App\Ticket;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Notifications\ExpiredDateNotification;
class NoticeExpiredDateCommand extends Command
{
protected $signature = 'command:notice_expired_date';
protected $description = 'send email to user to notice the expired date of his tickets.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->checkBefore1Week();
Common::makeLog($this->getName());
}
protected function checkBefore1Week()
{
$from = Carbon::today()->copy()->addDays(7)->format('Y-m-d H:i:s'); //ex. 2019-03-01 00:00:00
$to = Carbon::tomorrow()->copy()->addDays(7)->subSecond()->format('Y-m-d H:i:s');
$tickets = Ticket::whereBetween('expired_date', [$from, $to])->get();
$noticing_users = [];
foreach ($tickets as $i => $ticket) {
$noticing_users[$i] = $ticket['user_id'];
}
if ($noticing_users != []):
$users = User::find($noticing_users);
foreach ($users as $user) :
$user->notify(new ExpiredDateNotification($user, $expired_date = $from));
endforeach;
endif;
}
}
Common.php
namespace App\Console\Commands;
class Common
{
public static function makeLog($command_name)
{
$param = [
'command_name' => $command_name,
];
\Log::info('command executed', $param);
}
}
I solved this by my self.
I wrote cron like this but not work.
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Now, I write cron like this and it works.
*/5 * * * * cd /{project directory} && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1
The directory of php may depend on the server.
And about I type below on the terminal.
php artisan schedule:run
The ones place of the minutes of the time is 5,
the command returns
Running scheduled command
If the ones place of the minutes of the time is except of 5, it returns
No scheduled commands are ready to run.
I have installed https://github.com/laravel-notification-channels/webpush
in my project but when send notifications there are nothing. It doesnt work
This is laravel notifications documentation: https://laravel.com/docs/5.5/notifications
This is my code - I have created a notification:
class AccountApproved extends Notification {
use Queueable;
public function __construct()
{
//
}
public function via($notifiable)
{
return [WebPushChannel::class];
}
public function toArray($notifiable)
{
return [
'title' => 'Hello from Laravel!',
'body' => 'Thank you for using our application.',
'action_url' => 'https://laravel.com',
'created' => Carbon::now()->toIso8601String()
];
}
public function toWebPush($notifiable, $notification)
{
return WebPushMessage::create()
->title('Hello from Laravel!')
->icon('/notification-icon.png')
->body('Thank you for using our application.')
->action('View app', 'view_app');
}}
and I call Notification in my controller:
$when = Carbon::now();
$request->user()->notify((new AccountApproved)->delay($when));
But I Webpush doesnt work. What's wrong?
Make sure you are running queue worker like this:
php artisan queue:work
in command line. Otherwise queued notification won't be sent.
In case it doesn't help look at your error log and verify if there are any errors in there
For the method delay() to work you must add to your Notification implements ShouldQueue
class AccountApproved extends Notification implements ShouldQueue { ... }
and ofc use Illuminate\Contracts\Queue\ShouldQueue; before your class
I am using windows.
My code on \app\Console\Kernel.php is like this:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Commands\CustomCommand::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('custom:command')
->everyMinute();
}
protected function commands()
{
require base_path('routes/console.php');
}
}
My code on \app\Console\Commands\CustomCommand.php is like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class CustomCommand extends Command
{
protected $signature = 'custom:command';
protected $description = 'test cron job to update status on table order';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$id = 1;
DB::table('orders')
->where('id', $id)
->update(['status' => 2, 'canceled_at' => date("Y-m-d H:i:s")]);
}
}
I run php artisan list to see my cron job
After find my cron job (custom:command), then I run my cron job with like this : php artisan custom:command
It's successful update status = 2. After that I change the status manually again become 1, and then I wait one minute, it does not update status again
Is there anyone can help me?
You should also set cron on your local web server to run cron jobs.
How you change the status manually?
You change it in the database?
maybe the cron is running but 'id' int the database is equal to '2' and maybe this is why you dont see any change!
If you look for a better way to check if the Cron job is working
just add Log that will wroth to the log file
public function handle()
{
Log::info('Cron job working'); // you can also print variables
$id = 1;
DB::table('orders')
->where('id', $id)
->update(['status' => 2, 'canceled_at' => date("Y-m-d H:i:s")]);
}
Don't forget to had the Log to your source:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
use Log; // Here
class CustomCommand extends Command