samedi 21 juillet 2018

Load Eloquent Model Relationships Child Nodes in Laravel 5.1

I can't return $parent->child() | I get null;

Parent Model

class PrinterSetting extends Model
{
    protected $table = 'printer_settings';
    //fillables here
    protected $with = ['copies'];

    public function copies(){
        return $this->hasMany(\App\DB\PrinterCopy\PrinterCopy::class, 'printer_id');
    }

}

Child Model

class PrinterCopy extends Model
{
    protected $table = 'printer_copies';

    public function printer(){
        return $this->belongsTo(\App\DB\PrinterSetting\PrinterSetting::class, 'id', 'printer_id');
    }

}

Code in Controller:

$availablePrinters = $this->printerSetting->where('is_active', 1)->get();
foreach($availablePrinters as $availablePrinter)
{
   //working
   foreach($availablePrinter->copies() as $copy)
   {
   //Not working
   }
}

I can't find the reason why it's not working. I Tried to dump $availablePrinter->copies and it work, but ofcourse I can't insert it on foreach() loop. Please help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire