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:
CodePudding user response:
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;
}
}
CodePudding user response:
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.
}
}