0

I have an app, that using maatwebsite/laravel-excel lib, imports excel file with employees data. On each imported row app creates a new user. After that, it fetches all created users and sends to them an email with temp credentials.

Controller.php

public function import(Request $request) {
        ini_set('max_execution_time', '0'); 

        $import = new EmpImport();
        try {
            $import->import($request->file('file'));
        }catch (\Maatwebsite\Excel\Validators\ValidationException  $e){
            return back()->withErrors('Error: '.$e->getMessage());
        }

        $users = User::whereDate('created_at',Carbon::today())->whereNotNull('temp_pass')->get();
        $when = Carbon::now();
        if (count($users) > 0){
            foreach ($users as $user){
                $emp   = $user->emp;
                $error = null;

                if (!$emp->contact->exists() || $emp->contact->email == null)
                    continue;

                try{ 
                    $error = Mail::to($emp->contact->email)->later($when->addSeconds(5), new AccountCreated($emp,$user->temp_password));
                }catch (\Exception $e){
                     $error = $exception);
                }

                if ($error === null){
                    $user->temp_password = null;
                    $user->save();
                }
            }
        }

        ini_set('max_execution_time', '30'); 

        return back();
    }

It worked fine with 100 rows but when excel file became 1k+ Nginx started to give me 504 Gateway Timeout error, so I changed its configurations to:

fastcgi_read_timeout 300; 
fastcgi_send_timeout 300;

But on the next try, it showed 502 bad gateway :(....

Virtual Device
  • 1,650
  • 3
  • 10
  • 26
  • Long running scripts should be run via CRON and the command line instead of via a browser. Command line scripts do not have a timeout and aren't dependent on a browser, so don't have to deal with browser timeouts. If it's dependent on user input, then use a Queue to offload it to the commandline – aynber Feb 06 '20 at 19:24
  • @aynber thanks ! I've never heard of it before. Do you have any links to the related topic? – Virtual Device Feb 06 '20 at 19:29
  • https://laravel.com/docs/master/queues – aynber Feb 06 '20 at 19:30
  • @aynber what is the best way to show an error from the `handle()` method in job class back to UI? – Virtual Device Feb 07 '20 at 04:30
  • There really isn't, since once it's handed off to the queue, there's no more interaction with the user. You can instead send an email, or maybe use notifications to send it back to the user. – aynber Feb 07 '20 at 13:19

0 Answers0