skip to Main Content

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

2

Answers


  1. The reason this happens is that dd stands for “dump and die” so your first iteration goes through but you don’t check the rest because you use die(). A solution to this can be as simple as:

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

    Since you are only interested for the [0] position though a similar approach would be:

    public function getFormatosArticulo(Articulo $articulo) {
        $formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->first();
        if ($formatoRaw) {
            return $formatoRaw;
        }
    }
    
    Login or Signup to reply.
  2. 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.
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search