phplaravelkeyundefineddd

Undefined array key but with dd() works


I've done a query at Laravel and to check result content, I've used dd, but, for some reason, when I remove the dd(), it throws an exception sayint "Undefined array key 0". However, with dd DO find the key.

Code is this:

public function getFormatosArticulo(Articulo $articulo){
    $formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
    dd($formatoRaw[0]);
    $formato = $formatoRaw[0];
    return $formato;
}

And dd output is this:

dd output


Solution

  • I guess you are calling getFormatosArticulo function for multiple times, and passed not exists id into it. The get() function will always return a empty collection even if no data matched.

    Can you test your function use code below and check if id does exists or not?

    public function getFormatosArticulo(Articulo $articulo){
        try {
            $formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
            $formato = $formatoRaw[0];
            return $formato;
        catch (Exception $e) {
            dd($articulo->id); // i guess there is no articulo_id equal this in formato table.
        }
    }