我正在尝试导出数据库中的数据;特别是在场的所有客户,但也包括单个选定的客户。
我试图将代码设置为,当我单击按钮导出所有客户端时,将保存一个没有名称和扩展名的文件。
客户端导出类
class ClientsExport implements FromCollection
{
private $client = null;
public function __construct($client = null)
{
$this->client = $client;
}
public function collection(Client $client=NULL)
{
if ($this->client) {
return collect([$this->client]);
}
return Client::all();
}
}
经过几次尝试,我发现如果我删除下面代码中的if,那么就让它单独使用
return Excel::download(new ClientsExport,'clients.xlsx'(;
它工作正常,所以问题似乎是给它如果
客户端控制器
public function export(Client $client)
{
if($client){
return Excel::download(new ClientsExport($client), $client->surname . ' ' . $client->name . '.xlsx');
} else {
return Excel::download(new ClientsExport, 'clients.xlsx');
}
}
路线
Route::get('client-export/{client?}', [ClientController::class,'export'])->name('client.export');
查看刀片
我想导出所有客户端的按钮
<a class="btn btn-warning mb-5 py-3 px-4 mt-3 me-3 fs-5" href="{{ route('client.export') }}">Export all clients</a>
我想导出单个客户端的按钮
<a class="btn btn-warning" href="{{ route('client.export' , compact('client')) }}">Export</a>
问题是,当使用路由模型绑定时,将控制器方法定义为:public function export(Client $client)
将为您提供一个新的"空">CCD_ 2的实例,当您的路由定义中的客户端id为";"空">。因此,控制器方法中的以下检查将始终是正确的。
ClientController::导出(\App\Models\Client$Client(
if($client){
// ...
} else {
// ...
}
要解决此问题,您必须显式将Controller方法的参数设置为NULL
。这将指示Laravel的路由模型绑定系统为您提供CCD_ 4 CCD_;"空";当您的路由定义中的客户端id为"时,Client
模型(new AppModelsClient
(的实例;"空">。即:
ClientController类
// ...
public function export(AppModelsClient $client = null)
{
}
// ...
完整解决方案
客户端导出类
class ClientsExport implements FromCollection
{
public function __construct(private ?AppModelsClient $client = null)
{
}
public function collection()
{
return is_null($this->client)
? Client::all()
: collect([
$this->client
]);
}
}
ClientController类
// ...
public function export(AppModelsClient $client = null)
{
return Excel::download(new ClientsExport($client),
is_null($client)
? 'clients.xlsx'
: $client->surname . ' ' . $client->name . '.xlsx'
);
}
// ...