2017-01-30 29 views
0

我正在使用Laravel 5.4隊列。我想閱讀Excel並在幾秒鐘後讓數據庫進入該記錄。如何在Laravel 5.4隊列中傳遞函數?

$queue = Queue::later(10,'LogMsg', app('App\Http\Controllers\getFileController')->myfunc($name)); 
return $queue; 

這是我的通話功能,首先我可以這樣通過嗎?

public function myfunc($name) { 
    $f_data = Excel::load('public/invoices/'.$name, function($reader) { 
     })->get();  
    if(!empty($f_data) && $f_data->count()){ 
      foreach ($f_data as $key => $row){       
        $inv = new final_tables; 
        foreach ($row as $key1 => $col){ 
         $inv->$key1 = $row->$key1; 
        } 
        $inv->save(); 
      } 
     } 
    return 'done'; 
} 

回答

0

我覺得你真的想要做的是處理一個excel異步,你可以寫一個作業類做同樣的。作業類可以從控制器功能中調度並在後臺運行。

的相同功能的示例工作會是什麼樣子:

class ReadExcelAndSaveRecordsToDB implements ShouldQueue 
{ 
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; 

    protected $filePath; 

    /** 
    * Create a new job instance. 
    * 
    * @return void 
    */ 
    public function __construct(string $filePath) 
    { 
     $this->filePath = $filePath; 
    } 

    /** 
    * Execute the job. 
    * 
    * @return void 
    */ 
    public function handle() 
    { 
     $fileData = Excel::load($this->filePath, function($reader) { 
     })->get(); 

     //Whatever you want to do with the file here, for eg. create a DB entry 
     return 'done'; 
    } 
} 

現在你可以從你的控制器功能派遣同樣的工作,像這樣:

use Carbon\Carbon; 


public function someControllerAction(Request $request) 
{ 
    $filePath = //Save file and obtain filepath 

    $job = (new ReadExcelAndSaveRecordsToDB($filePath)) 
       ->delay(Carbon::now()->addMinutes(10)); 

    dispatch($job); 
} 

,並應爲你做它。