Murat Kaya
Murat Kaya

Reputation: 1321

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);
    }
}

Upvotes: 0

Views: 485

Answers (2)

Hilmi Erdem KEREN
Hilmi Erdem KEREN

Reputation: 1999

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'));

Upvotes: 3

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

According to your code, you're trying to access collection from a collection which is impossible, you should individually fetch a collection first and do your process

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


    foreach($companies as $company) {
        $retails_arr[] = $company->retails;
    }

    $retails = collect($retails_arr); // Gives Collection or
    // Or if you want to send array, try this
    $retails = $retails_arr; // Gives Array


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

Try this out hope this helps..

Upvotes: 0

Related Questions