I am trying to export the data present in my database; in particular all the clients present. So far there are no problems.
Now I would like to export to single client; I tried to set the code only that when I click to export the single client in an .xlsx file all clients are exported the same.
Here is my code:
ClientsExport Class
class ClientsExport implements FromCollection
{
/**
* @return IlluminateSupportCollection
*/
public function collection(Client $client=NULL)
{
return Client::all();
}
}
ClientController
public function export(Client $client=NULL)
{
if($client){
return Excel::download(new ClientsExport, $client->surname . ' ' . $client->name . '.xlsx');
} else {
return Excel::download(new ClientsExport, 'clients.xlsx');
}
}
Routes
Route::get('client-export/{client?}', [ClientController::class,'export'])->name('client.export');
View Blade
Button where I want to export all clients (this works fine)
<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>
Button where I want to export the individual client (PROBLEM HERE)
<a class="btn btn-warning" href="{{ route('client.export' , compact('client')) }}">Export</a>
export fuction update:
public function export(Client $client)
{
if($client){
dd($client);
return Excel::download(new ClientsExport($client), $client->surname . ' ' . $client->name . '.xlsx');
}
return Excel::download(new ClientsExport, 'clients.xlsx');
}
3
Answers
Create the property on the export. Make it able to assign it on creation. While making the collection dependent on if the client is present or not.
When you call it you can pass the client and it will on creation filter the collection based on the logic we just created.
You are alwayse returning the same data from your
ClientsExport
Class, so you’re not even using the$client
valiable, instead you are accessing the static classall()
of your Client model.So to refactor this you need to use your injected client in your class
then in your controller check if the Client is set or not and return appropriate Client instance
what is doing is first I get data from database of that particular user/client:
In Controller:
In Export class:
Try this I hope it work for you.