File: /var/www/vhost/disk-apps/qas.sports-crowd.com/app/Http/Controllers/Exports/ReportClients.php
<?php
namespace App\Http\Controllers\Exports;
use App\User;
use DateTime;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
class ReportClients implements FromQuery, WithHeadings, WithMapping
{
private $withOrders = false;
private $withoutOrders = false;
private $withOrdersLastFifteenDays = false;
// set column headers
public function headings(): array
{
return [
'Email',
'Nombres',
'Teléfono',
'Fecha registro',
'Abonado'
];
}
// report query. Be sure to not ->get() the results!
public function query()
{
return User::select(
'users.id',
'users.first_name',
'users.last_name',
'users.email',
'users.active',
'users.phone',
'users.created_at',
'users.is_subscriber'
)
->where('users.rol_id', 4)
->whereNull('users.deleted_at')
->when($this->withOrders, function($query) {
$query->whereIn('users.id', function ($query) {
$query->select('client_id')->from('orders');
});
})
->when($this->withoutOrders, function($query) {
$query->whereNotIn('users.id', function ($query) {
$query->select('client_id')->from('orders');
});
})
->when($this->withOrdersLastFifteenDays, function($query) {
$from = (new DateTime())->modify('-15 day');
$to = new DateTime();
$query->whereNotIn('users.id', function ($query) use ($from, $to) {
$query->select('client_id')->from('orders')->whereBetween('creation_date', [$from, $to]);
});
})
->orderBy('users.id', 'DESC')
;
}
public function withOrders()
{
$this->withOrders = true;
return $this;
}
public function withoutOrders()
{
$this->withoutOrders = true;
return $this;
}
public function withOrdersLastFifteenDays()
{
$this->withOrdersLastFifteenDays = true;
return $this;
}
public function map($user): array
{
return [
$user->email,
$user->first_name . ' ' . $user->last_name,
$user->phone,
$user->created_at,
$user->abonado > 0 ? 'SI' : 'NO'
];
}
}