I have two functions - 1 showing the results and 1 to download results that are on page.
The problem is that I can't find a way how to download only the results. Instead when I hit Download button it downloads all records in database.
This is what I have in my controler
public function index(Request $request)
{
$user = DB::table('downloads')
->select('user_id as downloader_id', DB::raw('COUNT(id) as count'))
->groupBy('user_id');
if(isset($request->startDate) && isset($request->dateEnd)) {
$user = $user->whereBetween(DB::raw("DATE_FORMAT(downloads.created_at, '%Y-%m-%d')"), [$request->startDate, $request->dateEnd]);
} elseif (isset($request->startDate)) {
$user = $user->where('created_at',$request->startDate);
}
$works=DB::table('users')
->joinSub($user, 'downloads_byuser', function ($join) {
$join->on('id', '=', 'downloads_byuser.downloader_id');
})
->select('users.id as user_id', 'users.name as name', 'users.email as email', 'count')
->get();
return view('admin.downloadsuser', compact("works"));
}
public function download(Request $request){
$headers = array(
// some headers
);
//creating the download file
$filename = public_path("Downloads.csv");
$handle = fopen($filename, 'w');
//adding the first row
fputcsv($handle, [
"Email",
"Downlaods",
]);
//adding the data from the array
foreach ($works as $each_user) {
fputcsv($handle, [
$each_user->email,
$each_user->count,
]);
}
fclose($handle);
return Response::download($filename, "Downloads.csv", $headers);
}
And this is in the blade
<form>
<input type="date" name="startDate" id="startDate">
<input type="date" name="dateEnd" id="dateEnd">
<button type="submit" > Filter </button>
</form>
<form action="{{ route('admin.works.download') }}">
<button type="submit" > Download </button>
</form>
<table >
<thead>
<tr>
<th>User</th>
<th>Email</th>
<th>Downloads</th>
</tr>
</thead>
<tbody>
@foreach($works as $work)
<tr>
<td>{{ $work->name }}</td>
<td>{{ $work->email }}</td>
<td>{{ $work->count }}</td>
</tr>
@endforeach
</tbody>
</table>
Any help is appreciated.
CodePudding user response:
Store the date when the search criteria are provided in the session, like this
\Session::put('startDate', $request->startDate);
\Session::put('dateEnd', $request->dateEnd);
After that in your download function retrieve the session dates. If none exists, the second parameter is returned instead.
$startDate = Session::get('startDate', '2022-02-11');
$dateEnd = Session::get('dateEnd', '2022-02-11');
You could just make them null, and have your query scope ignore them - which is essentially making the default export return all-time (unfiltered) records.
$startDate = Session::get('startDate', null);
$dateEnd = Session::get('dateEnd', null);
Or use carbon and return current date as default - \Carbon\Carbon::parse()