Murat Kaya Murat Kaya - 29 days ago 15
PHP Question

PHP error: Undefined property: Illuminate\Database\Eloquent\Collection::$retails

Hello I'm trying get my objects on laravel like this.

But I'm getting this error.

PHP error: Undefined property: Illuminate\Database\Eloquent\Collection::$retails on line 18


Also this is my code.

public function index(){
$retails = Auth::user()->companies->retails->all();


return view('retails/retails', compact('retails'));
}


Company Model

class Company extends Model
{
public function retails(){
$this->hasMany(Retail::class);
}
}


Retail Model

class Retail extends Model
{
public function company(){
return $this->belongsTo(Company::class);
}
}

Answer

You have many companies. That is why you get a collection from

Auth::user()->companies

When you call ->retails from the collection instance, you get the exception you wrote.

You have to eager load the companies with retails and then loop through them.

Like:

$u = auth()->user();
$u->load('companies.retails');

$userRetails = [];
$u->companies->each(function($company) use (&$userRetails) {
    $userRetails = array_merge($userRetails, $company->retails->toArray());
});

$userRetails = collect($userRetails);
return view('retails/retails', compact('userRetails'));