Maison012
Maison012

Reputation: 101

Laravel how to get auth user id on cronjob

I run a cronjob every minute and data returne, i save on db in a table notification. But here i need to save also user_id. I mean i know we can not find Auth::user()->id on cronjob but how can we get this user id?

 public function handle(ReminderEventServices $reminderServices)
    {
        // return 0;
        // $getLastReminders = $reminderServices->ReminderEvent(); 
        $getLastReminders = Reminder::orderBy('id', 'DESC')->get();

        return app('App\Http\Controllers\NotificationController')->store($getLastReminders);
}

I have send request to Notification controller , hoping there i can use there Auth but i was wrong.

    public function store($getLastReminders)
    {
        $user_id = Auth::user()->id;
        
        foreach($getLastReminders as $reminder) {
            if (!Notification::where('title', $reminder->title)->exists()) {
                $notification = Notification::create([
                    'title'         => $reminder->title,
                    'user_id'       => $user_id,
                    'description'   => $reminder->description,
                    'remindTime'    => $reminder->remindTime
                ]);
            }

            event(new ReminderEvent($reminder));
        }
    }

Upvotes: 0

Views: 487

Answers (1)

Oronatur
Oronatur

Reputation: 17

You should try another approach - the cron job is not supposed to handle users in that way. Consider trying an event listener or an observer instead. I've included the link to Laravels documentation on events for your convienience.

Upvotes: 1

Related Questions