简体   繁体   中英

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));
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM