Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jgravois's avatar

Can get boolean but can't get date from collection

I have an indefinite list of certificates that a technician can earn. I store them in a pivot table of techs and certs.

I am trying to create a certs attribute on the user. If I just try to return booleans, it works perfectly but if uncomment //$arrCerts[$award['slug']] = $fnd[0]->original['award_date']; and try to return the award date, I get this exception

ErrorException in Collection.php line 1456:
Undefined offset: 0

I var_dumped the $fnd variable and the date is definitely in there.

This is the method

public function getCertsAttribute()
    {
        $arrCerts = [];
        $certs = $this->certificates;

        $awards = EcoTechCertificate::all();

        foreach($awards as $award) {
            if($certs->contains('certificate_id', $award->id)) {
                $fnd = $certs->where('certificate_id', $award->id);
                $arrCerts[$award['slug']] = true;
                //$arrCerts[$award['slug']] = $fnd[0]->original['award_date'];
            } else {
                $arrCerts[$award['slug']] = false;
            } // end if
        } // end foreach

        return collect($arrCerts);
    } // end function
0 likes
3 replies
stanb's avatar

Can you var_dump $fnd? The error say that index 0 is not set.

stanb's avatar
stanb
Best Answer
Level 3

Aha, I see your mistake. You forgot ->get() or ->first() behind 1454. Since you want the first result you probably want to add ->first().

This will probably be the correct code

public function getCertsAttribute()
    {
        $arrCerts = [];
        $certs = $this->certificates;

        $awards = EcoTechCertificate::all();

        foreach($awards as $award) {
            if($certs->contains('certificate_id', $award->id)) {
                $fnd = $certs->where('certificate_id', $award->id)->first();
                $arrCerts[$award['slug']] = true;
                $arrCerts[$award['slug']] = $fnd->original['award_date'];
            } else {
                $arrCerts[$award['slug']] = false;
            } // end if
        } // end foreach

        return collect($arrCerts);
    } // end function

Please or to participate in this conversation.