laravel - 'Auth' is not working in cron schedule - laravel

I have created a cron job in the 'commands' files. and I want to get the id of the user using Auth::user()->id but I am getting the error. Where am I missing?
My error:
Trying to get property 'id' of non-object
My controller
use Illuminate\Support\Facades\Auth;
protected $signature = 'orders:minute';
public function handle()
{
$id = Auth::user()->id;
}
Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('orders:minute')
->everyMinute();
}

You can't do that because a user doesn't run the scheduled command, so Auth::user() object will always be null.
To fix this, you can save User Id in Database and fetch the data on scheduled command execution.

You can't do that because a user doesn't run the cron scheduled.

For the use case you're showing you'd have to provide it yourself, for example as a command argument:
protected $signature = 'command:Orders {user_id : id of the recipient model}';
public function handle() {
$user_id = $this->argument('user_id');
$user = User::findOrFail($user_id);
// other commands
}
So executing php artisan command:SendNotification 1 would act as if user 1 was authenticated.

Cron means to run something automatically. You can't do that because a user doesn't run the cron scheduled. You only get Auth::user()->id when the user login

Related

How can I run scheduler every one minute in Laravel without setting cron job?

I want to run the scheduler in every minute on the server without setting the cron job with ssh .Please let me know Is there any way to do this ?
Thanks
Assumption: you have set cron job to your project directory
Create a command using
php artisan make:command CommandName
add your logic under handle function
public function handle()
{
//add your logic here
}
register your command under Kernel.php under $commands array
protected $commands = [
Commands\Test::class,
];
schedule command under
protected function schedule(Schedule $schedule)
{
$schedule->command('command:name')->everyMinute();
}

How to store records on the end of the day in laravel

For example, If user forgot to approve till the end of the day a message will store to the database at the end of the day. I used the carbon format as below.
if (Carbon::now()->endOfDay()->eq(Carbon::parse($phaseValue->end_date)->endOfDay())) {
// add records here
}
You will have to set up a task scheduler that will check if a specific condition has been met at the end of the day. if not then it will do the insertion in DB or anything according to your business logic. Laravel provides task scheduling, have a look:
https://laravel.com/docs/8.x/scheduling
You could create a cron job that would run every day at the given time. To do that, create a new command:
php artisan make:command YourCommand
Then, your command would look something like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class YourCommand extends Command
{
//Name that will be used to call command
protected $signature = 'your:command';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
//Here you will handle all the logic. For ex:
$record = App/Example::first();
//Implement condition that will determine if the record will be updated
$record->update();
}
}
After that, inside App/Console/Kernel.php create the schedule for that command:
protected function schedule(Schedule $schedule)
{
//Name that you gave it in the protected $signature = 'your:command';
$schedule->command('your:command')->dailyAt('23:30');
}
This way the command will be run every day at 23:30 and you can update your records any way you want. You can read more about task scheduling & commands on the official docs.

Iterate over serviceproviders in laravel cron

I have inherited this laravel app and still get accustomed to the framework.
At the moment I try to figure out the "best-practise-way" of iterating through "Service Providers" in a cron job. I have set up the schedule, but I know that just creating an object (or object factory) is probably a big no-no.
How can I get access to an array of all the components in this cron job. something with singeltons probably.
The code:
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$some_array = get_all_the_company_components_or_eloquents();
foreach( $some_array as $company )
{
$company->yay("yay");
}
})->daily();
}

Does Laravel 6 disable observers in factories / tests?

Ive just written an observer thats sends an e-mail whenever a user is created.
class UserObserver
{
public function created(User $user)
{
Mail::to($user)->send(new UserAccountCreated(
app('auth.password.broker')->createToken($user),
$user
));
}
}
I ran phpunit to test if my observer works, and it passed. However I was expecting to get an email for each time my tests create a user.
For example:
/** #test */
public function an_admin_can_view_all_clients()
{
$user = factory(User::class)->create(['is_admin' => true]);
$client = factory(Client::class)->create();
$client2 = factory(Client::class)->create();
$this->actingAs($user)->get(route('clients.index'))
->assertSuccessful()
->assertSee($client->name)
->assertSee($client2->name);
}
I would expect an email to be sent when that factory creates the user. But I don't receive one in Mailtrap.
Just wondering if and where laravel disables my observer being triggered when my factory creates that user.
No you have to disable it yourself by using Model::withoutEvents()
For example:
$user = User::first();
User::withoutEvents(function () use ($user) {
$user->delete();
});
Also in this specific case you can also use the Mail fake system provided by Laravel itself

Call to a member function notify() on integer in LARAVEL 5.8

I am working on a task schedule. The flow is I need to send notification as a reminder for their duedate.
here's my console\command\remindDuedate
class remindDuedate extends Command
{
protected $signature = 'remindDuedate:run';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
while (true) {
$loanapplications = LoanApplication::where('archive',false)->where('status','=',2)->get();
foreach ($loanapplications as $application) {
$user = $application->user_id;
$date_approval = Carbon::createFromTimestamp(strtotime($application->date_approval));
$duration = $application->loanDuration->num_days;
$duedate_warning = $duration-3;
$reminder_date = $date_approval->addDays($duedate_warning)->toDateString();
$now = Carbon::now('Asia/Manila')->toDateString();
$duedate = Carbon::now('Asia/Manila')->addDays(3)->toDateString();
if($reminder_date == $now) {
$user->notify(new remindDuedateNotif());
}
}
}
}
}
php artisan remindDuedate:run
remindDuedateNotif
Why do I getting the "Call to a member function notify() on integer"
Thank you in advance!
You are not fetching the user, therefor the user is still an integer, set it like so.
$user = User::find($application->user_id);
EDIT
As you can see your notification takes a user as the first argument. Therefor send it with it.
$user->notify(new remindDuedateNotif($user));
This is weird to send and notify on the User object and pass it. You are in luck as every $notifiable parameter is actually an user, as it would be the object you send it from.
So remove $user from __contruct() and everywhere you access the user, you can do the following.
'user_id' => $notifiable->id,
1) the User Model should have the notifiable trait
Illuminate\Notifications\Notifiable
2) you need to add a relation between the application and user in thee application model
public function user()
{
return $this->belongsTo(User::class);
}
3) notify the application user :
$application->user->notify(new remindDuedateNotif());

Resources