Limit sending email Laravel in once schedule task - windows

I have problem with limit email exchange from SMTP. I have counting table with specific column. total is 201. that total will send email automatic with schedule task on the server.
Counting TOTAL
can I send email per batch using laravel as much as 201 email in once send email?
cronEmail
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'email:reminder';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$this->updateMailConfig();
$check = DB::table('a_kpi')->join('d_mem','k_created_by','m_id')
->leftjoin('a_kpid','kd_kpi_id','k_id')
->where('k_status_id',1)
->where(function($query){
$query->where('kd_status_id','=','In Progress')
->orwhere('kd_status_id','=',null)
->orwhere('kd_status_id','=')
->orwhere('kd_status_id','=','null')
->orwhere('kd_status_id','=',"null");
})
->get();
$dt = date("Y-m-d");
$dtdt = date( "Y-m-d", strtotime( "$dt +10 day" ) );
for ($i=0; $i <count($check); $i++) {
if ($check[$i]->kd_duedate == $dtdt) {
$mail = $check[$i]->m_email;
Mail::send('mail.tes',
['pesan' => 'KPI INFORMATION',
'k_label' => $check[$i]->k_label,
'kd_tacticalstep' => $check[$i]->kd_tacticalstep,
'kd_duedate' => $check[$i]->kd_duedate],
function ($message) use ($mail)
{
$message->subject('REMINDER');
$message->to($mail);
});
$data = DB::table('d_log_reminder')
->insert([
'dlr_id'=>$check[$i]->k_id,
'dlr_kpi_id'=>$check[$i]->k_id,
'dlr_kpid_id'=>$check[$i]->kd_id,
'dlr_tacticalstep'=>$check[$i]->kd_tacticalstep,
'dlr_label'=>$check[$i]->k_label,
'dlr_duedate'=>$check[$i]->kd_duedate,
'dlr_created_by'=>$check[$i]->k_created_by,
'dlr_send_to'=>$mail
]);
}
}
// $check = DB::table('d_mem')->where('m_username','admin')->update(['m_code'=>'cor'.date('d-m-y h:i:s')]);
}
}
Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use App\Helper\ConfigUpdater;
use Mail;
use DB;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
use ConfigUpdater;
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
'App\Console\Commands\cronEmail'
//
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('email:reminder')
->everyMinute();
}
/**
* Register the Closure based commands for the application.
*
* #return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}

Related

Laravel job failed

I use Laravel 8 with supervisor.
I have an error on a few jobs in my application.
All jobs run in about 3 seconds.
I have a 60 second timeout and a 90 second retry_after.
There are only a few jobs that fail per day out of about 3000 jobs. I have the jobs of a client which fails all the time I don't know why.
On some jobs I get the following error:
has been attempted too many times or run too long. The job may have previously timed out. {"exception":"[object] (Illuminate\Queue\MaxAttemptsExceededException(code: 0)
I think I have an error because of the middleware, when I remove it it works.
job.php
class UpdateTimeslots implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 3;
protected $officeId;
protected $startDate;
protected $endDate;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(int $officeId, string $startDate = null, string $endDate = null)
{
$this->onQueue('availabilities');
$this->officeId = $officeId;
$this->startDate = $startDate;
$this->endDate = $endDate;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
app(TimeslotMergedService::class)->update([$this->officeId], $this->startDate, $this->endDate);
}
/**
* Get the middleware the job should pass through.
*
* #return array
*/
public function middleware()
{
return [(new WithoutOverlapping($this->officeId))];
}
/**
* Handle a job failure.
*
* #param \Throwable $exception
* #return void
*/
public function failed(\Throwable $exception)
{
Log::error([
'office_id' => $this->officeId,
'start_date' => $this->startDate,
'end_date' => $this->endDate,
'error' => $exception->getMessage()
]);
}
}
queue.php
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => ['tasks', 'queue'],
'retry_after' => 90,
'after_commit' => false,
],
laravel-worker.conf
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/app/artisan queue:work --queue=tasks,default --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=welrdv
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/worker.log
stopwaitsecs=3600
Can you help me please ?
UPDATE
here is the middleware code:
<?php
namespace Illuminate\Queue\Middleware;
use Illuminate\Container\Container;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Support\InteractsWithTime;
class WithoutOverlapping
{
use InteractsWithTime;
/**
* The job's unique key used for preventing overlaps.
*
* #var string
*/
public $key;
/**
* The number of seconds before a job should be available again if no lock was acquired.
*
* #var \DateTimeInterface|int|null
*/
public $releaseAfter;
/**
* The number of seconds before the lock should expire.
*
* #var int
*/
public $expiresAfter;
/**
* The prefix of the lock key.
*
* #var string
*/
public $prefix = 'laravel-queue-overlap:';
/**
* Create a new middleware instance.
*
* #param string $key
* #param \DateTimeInterface|int|null $releaseAfter
* #param \DateTimeInterface|int $expiresAfter
* #return void
*/
public function __construct($key = '', $releaseAfter = 0, $expiresAfter = 0)
{
$this->key = $key;
$this->releaseAfter = $releaseAfter;
$this->expiresAfter = $this->secondsUntil($expiresAfter);
}
/**
* Process the job.
*
* #param mixed $job
* #param callable $next
* #return mixed
*/
public function handle($job, $next)
{
$lock = Container::getInstance()->make(Cache::class)->lock(
$this->getLockKey($job), $this->expiresAfter
);
if ($lock->get()) {
try {
$next($job);
} finally {
$lock->release();
}
} elseif (! is_null($this->releaseAfter)) {
$job->release($this->releaseAfter);
}
}
/**
* Set the delay (in seconds) to release the job back to the queue.
*
* #param \DateTimeInterface|int $releaseAfter
* #return $this
*/
public function releaseAfter($releaseAfter)
{
$this->releaseAfter = $releaseAfter;
return $this;
}
/**
* Do not release the job back to the queue if no lock can be acquired.
*
* #return $this
*/
public function dontRelease()
{
$this->releaseAfter = null;
return $this;
}
/**
* Set the maximum number of seconds that can elapse before the lock is released.
*
* #param \DateTimeInterface|int $expiresAfter
* #return $this
*/
public function expireAfter($expiresAfter)
{
$this->expiresAfter = $this->secondsUntil($expiresAfter);
return $this;
}
/**
* Set the prefix of the lock key.
*
* #param string $prefix
* #return $this
*/
public function withPrefix(string $prefix)
{
$this->prefix = $prefix;
return $this;
}
/**
* Get the lock key for the given job.
*
* #param mixed $job
* #return string
*/
public function getLockKey($job)
{
return $this->prefix.get_class($job).':'.$this->key;
}
}

How to send only one event in Pusher channel and then for database notification store for all users

I've created a broadcast channel App.Models.Admin.Notify where all the admin users will be subscribed to this channel by default.
<?php
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('App.Models.Admin.Notify', function ($m) {
return !is_null($m) && $m->getMorphClass() === 'admin';
});
And this is the Notifications/Base.php where i've set ['database', 'broadcast', OneSignal::class] as notification channels
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\BroadcastMessage;
use NotificationChannels\OneSignal\OneSignalMessage;
use App\Channels\OneSignal;
abstract class Base extends Notification implements ShouldBroadcast, ShouldQueue
{
use Queueable;
public $model;
protected string $icon;
public function __construct(mixed $m = null)
{
$this->model = $m;
}
/**
* Get notify id
*
* #return string
*/
protected function getNotifyId(): string
{
return $this->id;
}
/**
* Get icon path
*
* #return string
*/
protected function getIcon(): string
{
return asset('favicon.ico');
}
/**
* Get notification link
*
* #return string
*/
protected function getLink(): string
{
return asset('favicon.ico');
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return \App\Channels\PusherBeams\PusherMessage
*/
public function via($notifiable)
{
return [
'database',
'broadcast',
OneSignal::class
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return array_merge(
[
'link' => $this->getLink(),
'icon' => $this->getIcon(),
],
$this->getData($notifiable)
);
}
/**
* Get data of message.
*
* #param mixed $notifiable
* #return array
*/
protected function getData($notifiable)
{
return [
'title' => 'hello',
'body' => 'world'
];
}
/**
* Create onesignal message of Web
* #param mixed $notifiable
* #return \NotificationChannels\OneSignal\OneSignalMessage
*/
public function toWeb($notifiable)
{
$data = $this->toArray($notifiable);
return OneSignalMessage::create()
->setSubject($data['title'])
->setBody($data['body'])
->setUrl($data['link']);
}
/**
* Create onesignal message of Android
* #param mixed $notifiable
* #return \NotificationChannels\OneSignal\OneSignalMessage
*/
public function toAndroid($notifiable)
{
$data = $this->toArray($notifiable);
return OneSignalMessage::create()
->setSubject($data['title'])
->setBody($data['body'])
->setData('url', str_replace('https://', 'gamepts://', $data['link']));
}
/**
* Websocket message
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\BroadcastMessage
*/
public function toBroadcast($notifiable)
{
return (new BroadcastMessage($this->toArray($notifiable)))->onQueue('pusher');
}
}
So this is the basic setup for my Notifications and broadcasting.
I've a job which runs every minutes and if any reports are found then it should send the notification if any reports are found.
<?php
namespace App\Console\Commands;
use Carbon\Carbon;
use App\Models\MerchantDeposit;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
class CheckCashIn extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'check:cashin';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Check expiration of cash in orders';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$setting = app(\App\Settings\CurrencySetting::class)->currency;
$expired_limit = app(\App\Settings\AdminSetting::class)->expired_payin_limit_notify;
$reports = [];
foreach ($setting as $currency => $s) {
$expired_minutes = $s['expired_minutes'];
$k = MerchantDeposit::where('status', MerchantDeposit::STATUS['PENDING'])
->where('currency', $currency)
->where('created_at', '<=', Carbon::now()->subMinutes($expired_minutes))
->update(['status' => MerchantDeposit::STATUS['EXPIRED']]);
$o = MerchantDeposit::where('merchant_deposits.status', MerchantDeposit::STATUS['EXPIRED'])
->join('reseller_bank_cards', 'reseller_bank_cards.id', 'merchant_deposits.reseller_bank_card_id')
->join('resellers', 'resellers.id', 'reseller_bank_cards.reseller_id')
->where('merchant_deposits.currency', $currency)
->where('merchant_deposits.created_at', '<=', Carbon::now()->subMinutes($expired_minutes))
->having(DB::raw('COUNT(resellers.name)'), '>=', $expired_limit)
->select('resellers.name', DB::raw('COUNT(resellers.name) AS total_expired'), DB::raw('TRUNCATE(SUM(merchant_deposits.amount), 2) AS total_amount'), 'merchant_deposits.currency')
->groupBy('resellers.name', 'merchant_deposits.currency')
->get();
if (!empty($o->toArray()) && $k > 0) {
$reports[$currency] = [];
foreach ($o as $k => $v) {
$reports[$currency][$v->name] = $v->total_expired;
$reports[$currency]['Total Amount'] = $v->total_amount;
}
}
}
if (!empty($reports)) {
Notification::send(\App\Models\Admin::all(), new \App\Notifications\DepositExpiredReport($reports));
}
}
}
And in Model/Admin.php i've set receivesBroadcastNotificationsOn to update the channel name for the broadcast to send into pusher.
<?php
namespace App\Models;
use App\Trait\HasJWTSubject;
use App\Trait\UserLogsActivity;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Illuminate\Notifications\Notifiable;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Spatie\Permission\Traits\HasRoles;
/**
* Model of admin
* #package Models
*/
class Admin extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, HasFactory, HasJWTSubject;
use UserLogsActivity;
use Notifiable;
use HasRoles;
protected $fillable = [
'name',
'username',
'password',
'status',
'timezone'
];
protected $hidden = [
'password',
];
protected $casts = [
'status' => 'boolean',
];
public const STATUS = [
'DISABLED' => false,
'ACTIVE' => true,
];
public function getIsSuperAdminAttribute()
{
return $this->hasRole('Super Admin');
}
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::needsRehash($value) ? Hash::make($value) : $value;
}
public function devices()
{
return $this->morphMany(Device::class, 'user');
}
public function receivesBroadcastNotificationsOn()
{
return 'App.Models.Admin.Notify';
}
}
When the notification is triggered from Notification::send(\App\Models\Admin::all(), new \App\Notifications\DepositExpiredReport($reports)); it will send broadcast notification multiple times to same broadcast channel as shown in the screenshot below
From Notification::send(\App\Models\Admin::all(), new \App\Notifications\DepositExpiredReport($reports)); it is fine to save the notification records for all the admin in database notification but for pusher i want the notification event to sent only once instead of sending multiple times ie 'x' number of admins.
Lets say i have 100 admin users then now pusher will send the event to same channel 100 times. So i want to minimize the pusher event to just 1 channel where all the admin users subscribed can receive the notification but it should also save the records for 100 users in the notification table of database.

Laravel 5.8 scheduler is not running commands

This question is asked before but non of the answers work for me. This is the Kernel.php
<?php
namespace App\Console;
use App\Console\Commands\TestRunKernel;
use App\Log;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
TestRunKernel::class
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
Log::create([
'body' => 'test for log'
]);
$schedule->call(function () {
Log::create([
'body' => 'test2 for log'
]);
})->everyMinute();
$schedule->command('test:run')->everyMinute();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
and this is the command
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\User\Entities\User;
class TestRunKernel extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'test:run';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$user = User::find(1);
$user->update([
'file' => 1
]);
}
}
The Kernel.php is running by cron job and test for log message is written in Log model. Hence I am sure the file is running by server. But when I use $schedule it doesn't work and non of the commands work. How can I fix this?
Thanks in advance.

Extending and customizing Laravel Reset Password Logic

Does anybody know how to customize ResetPassword logic in Laravel. I want to use custom field 'phone' vs 'email'. Small workaround with create_passwords_resets migration and done
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('phone')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
But i've started to get exceptions on absent field 'email' users tables simply doesn't have it all.
I'm just trying to use Password::Facade like
$status = Password::sendResetLink($request->only('phone'));
Why in such customizable platform hard-coded things like DatabaseTokenRepository even exist?
public function exists(CanResetPasswordContract $user, $token)
{
$record = (array) $this->getTable()->where(
'email', $user->getEmailForPasswordReset()
)->first();
return $record &&
! $this->tokenExpired($record['created_at']) &&
$this->hasher->check($token, $record['token']);
}
How can i override it?
If i try to implement one of the answers on Stack doing this:
namespace App\Auth;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Auth\Passwords\DatabaseTokenRepository as DatabaseTokenRepositoryBase;
use Illuminate\Support\Carbon;
class DatabaseTokenRepository extends DatabaseTokenRepositoryBase
{
public function create(CanResetPasswordContract $user)
{
$email = $user->getEmailForPasswordReset();
$mobile = $user->getMobileForPasswordReset();
$this->deleteExisting($user);
$token = $this->createNewToken();
$this->getTable()->insert($this->getPayload($email, $mobile, $token));
return $token;
}
protected function deleteExisting(CanResetPasswordContract $user)
{
return $this->getTable()
->where("email", $user->getEmailForPasswordReset())
->orWhere("mobile", $user->getMobileForPasswordReset())
->delete();
}
protected function getPayload($email, $mobile, $token): array
{
return [
"email" => $email,
"mobile" => $mobile,
"token" => $this->hasher->make($token),
"created_at" => new Carbon(),
];
}
public function exists(CanResetPasswordContract $user, $token)
{
$record = (array)$this->getTable()
->where("email", $user->getEmailForPasswordReset())
->orWhere("mobile", $user->getMobileForPasswordReset())
->first();
return $record &&
! $this->tokenExpired($record["created_at"]) &&
$this->hasher->check($token, $record["token"]);
}
It throws exception like:
"Declaration of App\Auth\DatabaseTokenRepository::getPayload($email, $mobile, $token) must be compatible with Illuminate\Auth\Passwords\DatabaseTokenRepository::getPayload($email, $token)"
Valid workaround is original #miken32 answer on Password reset in Laravel 5.5 by email or mobile
But with complete re-implementation of DatabaseTokenRepository class, like:
<?php
namespace App\Auth;
use Carbon\Traits\Creator;
use Illuminate\Auth\Passwords\TokenRepositoryInterface;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
class DatabaseTokenRepository implements TokenRepositoryInterface
{
/**
* The database connection instance.
*
* #var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
/**
* The Hasher implementation.
*
* #var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* The token database table.
*
* #var string
*/
protected $table;
/**
* The hashing key.
*
* #var string
*/
protected $hashKey;
/**
* The number of seconds a token should last.
*
* #var int
*/
protected $expires;
/**
* Minimum number of seconds before re-redefining the token.
*
* #var int
*/
protected $throttle;
/**
* Create a new token repository instance.
*
* #param \Illuminate\Database\ConnectionInterface $connection
* #param \Illuminate\Contracts\Hashing\Hasher $hasher
* #param string $table
* #param string $hashKey
* #param int $expires
* #param int $throttle
* #return void
*/
public function __construct(ConnectionInterface $connection, HasherContract $hasher,
$table, $hashKey, $expires = 60,
$throttle = 60)
{
$this->table = $table;
$this->hasher = $hasher;
$this->hashKey = $hashKey;
$this->expires = $expires * 60;
$this->connection = $connection;
$this->throttle = $throttle;
}
/**
* Determine if the token has expired.
*
* #param string $createdAt
* #return bool
*/
protected function tokenExpired($createdAt)
{
return Carbon::parse($createdAt)->addSeconds($this->expires)->isPast();
}
/**
* Determine if the given user recently created a password reset token.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #return bool
*/
public function recentlyCreatedToken(CanResetPasswordContract $user)
{
$record = (array) $this->getTable()->where(
'phone', $user->getPhoneForPasswordReset()
)->first();
return $record && $this->tokenRecentlyCreated($record['created_at']);
}
/**
* Determine if the token was recently created.
*
* #param string $createdAt
* #return bool
*/
protected function tokenRecentlyCreated($createdAt)
{
if ($this->throttle <= 0) {
return false;
}
return Carbon::parse($createdAt)->addSeconds(
$this->throttle
)->isFuture();
}
/**
* Delete a token record by user.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #return void
*/
public function delete(CanResetPasswordContract $user)
{
$this->deleteExisting($user);
}
/**
* Delete expired tokens.
*
* #return void
*/
public function deleteExpired()
{
$expiredAt = Carbon::now()->subSeconds($this->expires);
$this->getTable()->where('created_at', '<', $expiredAt)->delete();
}
/**
* Create a new token for the user.implements TokenRepositoryInterface
*
* #return string
*/
public function createNewToken()
{
return hash_hmac('sha256', Str::random(40), $this->hashKey);
}
/**
* Get the database connection instance.
*
* #return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Begin a new database query against the table.
*
* #return \Illuminate\Database\Query\Builder
*/
protected function getTable()
{
return $this->connection->table($this->table);
}
/**
* Get the hasher instance.
*
* #return \Illuminate\Contracts\Hashing\Hasher
*/
public function getHasher()
{
return $this->hasher;
}
public function create(CanResetPasswordContract $user)
{
$mobile = $user->getPhoneForPasswordReset();
$this->deleteExisting($user);
$token = $this->createNewToken();
$this->getTable()->insert($this->getPayload($mobile, $token));
return $token;
}
protected function deleteExisting(CanResetPasswordContract $user)
{
return $this->getTable()
->where('phone', $user->getPhoneForPasswordReset())
->delete();
}
protected function getPayload($mobile, $token)
{
return ['phone' => $mobile, 'token' => $this->hasher->make($token), 'created_at' => new Carbon];
}
public function exists(CanResetPasswordContract $user, $token)
{
$record = (array) $this->getTable()
->where('phone', $user->getPhoneForPasswordReset())
->first();
return $record &&
! $this->tokenExpired($record['created_at']) &&
$this->hasher->check($token, $record['token']);
}
}

Laravel 5.0 : Task scheduling

I am using Laravel 5.0.*, Now I want to implement cron job in my application.
I searched a lot but I get nothing, all the example and video tutorials are related to 5.1 and 5.3 even I search in laravel.com for task scheduling under 5.0 version but it showing nothing
Reference video link : video link
And after using above video reference, I am getting below error in terminal.
[2016-11-02 08:47:06] local.ERROR: exception 'InvalidArgumentException' with message 'There are no commands defined in the "cron" namespace.' in D:\harendar\htdocs\nkbuild\vendor\symfony\console\Symfony\Component\Console\Application.php:501
/app/Console/Kernel.php
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
'App\Console\Commands\Inspire',
'App\Console\Commands\LogDemo',
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')
->hourly();
$schedule->command('log:demo')->emailOutputTo('harendar#solutionavenues.com');
}
}
/app/Console/Commands/LogDemo.php
<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class LogDemo extends Command {
/**
* The console command name.
*
* #var string
*/
protected $name = 'log:demo';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Log Demo command.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function fire()
{
\log::info('I was here # ', \Carbon\Carbon::now());
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return [
['example', InputArgument::REQUIRED, 'An example argument.'],
];
}
/**
* Get the console command options.
*
* #return array
*/
protected function getOptions()
{
return [
['example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null],
];
}
}
Hello First you need to run command : php artisan make:console test(command name).
Then you find one test.php command created under app/Console/Commands/test.php .this looks like:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class test extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'test';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
//
}
}

Resources