How to return empty collection on push

41 Views Asked by At

I have a problem with the following code. When performing the push inside the collection, I have an item with an empty collection when both conditions are false.

$admins = collect(new User);
$owner = collect(new User);

if (config('personal.mailing_technician')) {
    $owner = $event->ticket->ownedBy;
}

if (config('personal.mailing_admin')) {
    $admins = User::query()->role('admin')->get();
}

$sentTo = $admins->push($owner);

if ($senTo->isNotEmpty()) {
    .......
}

What could I do to make it empty if both conditions are false?

1

There are 1 best solutions below

0
Karl Hill On

To make sure that $sentTo is an empty collection when both conditions are false...

$admins = collect(new User);
$owner = collect(new User);

if (config('personal.mailing_technician')) {
    $owner = $event->ticket->ownedBy;
}

if (config('personal.mailing_admin')) {
    $admins = User::query()->role('admin')->get();
}

$sentTo = collect(); // Initialize an empty collection

if ($admins->isNotEmpty() || $owner->isNotEmpty()) {
    $sentTo = $admins->push($owner);
}

if ($sentTo->isNotEmpty()) {
    // Do something
}