gpt4 book ai didi

laravel - 从 Laravel Excel 导入中返回变量

转载 作者:行者123 更新时间:2023-12-03 19:44:25 26 4
gpt4 key购买 nike

下面的代码,基本示例,但我想返回错误(请参阅 import 后注释掉的 if 语句)。我如何将变量从“导入”类传递回 Controller ?

Controller :

public function resultsImport(Request $request)
{
//validate the xls file
$this->validate($request, array('student_results_import_file' => 'required'));

if($request->hasFile('student_results_import_file')){
$extension = File::extension($request->student_results_import_file->getClientOriginalName());
if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {

Excel::import(new StudentResultsImport, $request->file('student_results_import_file'));
// if $ignore_count>0 --> do stuff
return redirect('/baadmin/students')->with('flash_message', ['success','Results Imported Successfully','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" imported successfully!']);
} else {
return redirect('/baadmin/students')->with('flash_message', ['error','Results Import Failed','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" import failed. File is a '. $extension .' file. Please upload a valid xls/csv file.']);
}
}
}

进口
public function collection(Collection $rows)
{
set_time_limit(300);
$ignore_count = 0;

foreach ($rows as $row) {
if ($row[8] != '') {
//import
}
else {
$ignore_count++;
//$ignore_count is just a simple example, ultimately would probably have an array of the various errors detected on the various rows
}
}
}

最佳答案

设法在文档中找到了适当的答案,引用了“Getters”:
https://docs.laravel-excel.com/3.1/architecture/objects.html#getters

例如:

namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;

class UsersImport implements ToModel
{
private $rows = 0;

public function model(array $row)
{
++$this->rows;

return new User([
'name' => $row[0],
]);
}

public function getRowCount(): int
{
return $this->rows;
}
}

完成导入后,我们可以使用 getter 请求状态。
$import = new UsersImport;
Excel::import($import, 'users.xlsx');

dd('Row count: ' . $import->getRowCount());

关于laravel - 从 Laravel Excel 导入中返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com