gpt4 book ai didi

excel - 如何将参数传递给 Laravel Excel 的导出文件以进行 DB 查询

转载 作者:行者123 更新时间:2023-12-03 22:53:21 25 4
gpt4 key购买 nike

将 id 变量传递给“where”请求以获取与 id 匹配的数据库条目,并使用 Laravel Excel 将这些条目导出到 Excel 工作表。我似乎找不到传递变量的方法。

我的 Controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\MttRegistrationsExport;
use Maatwebsite\Excel\Facades\Excel;

class ExcelController extends Controller
{
public function export($id)
{
return Excel::download(new MttRegistrationsExport, 'MttRegistrations.xlsx', compact('id'));
}
}

我的导出文件:
<?php

namespace App\Exports;

use App\MttRegistration;
use Maatwebsite\Excel\Concerns\FromCollection;

class MttRegistrationsExport implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return MttRegistration::where('lifeskill_id',$id)->get()([
'first_name', 'email'
]);
}
}

我的路线:
Route::get('/mtt/attendance/{id}',[
'as' => 'mtt.attendance',
'uses' => 'ExcelController@export']);

最佳答案

通过将 id 传递给 MttRegistrationsExport 类进行修改。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\MttRegistrationsExport;
use Maatwebsite\Excel\Facades\Excel;

class ExcelController extends Controller
{
public function export(Request $request)
{
return Excel::download(new MttRegistrationsExport($request->id), 'MttRegistrations.xlsx');
}
}

现在让我们设置一个构造函数,以便您可以将 id 传递给 MttRegistrationsExport 类。
<?php

namespace App\Exports;

use App\MttRegistration;
use Maatwebsite\Excel\Concerns\FromCollection;

class MttRegistrationsExport implements FromCollection
{


protected $id;

function __construct($id) {
$this->id = $id;
}

/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return MttRegistration::where('lifeskill_id',$this->id)->get()([
'first_name', 'email'
]);
}
}

关于excel - 如何将参数传递给 Laravel Excel 的导出文件以进行 DB 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57153985/

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