user13729875
user13729875

Reputation:

Laravel get parent attributes

I started working on a small project, i have two models Building & Apartment, each Building can have many apartments.

so i have created a relationship between the models but i get an error when i try to access to the parent ( Building )

This is my models :

// Building.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Apartment;

class Building extends Model
{
    protected $guarded = [];

    public function apartment(){
        return $this->hasMany(Apartment::class);
    }
}

// Apartment.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Building;

class Apartment extends Model
{
    protected $guarded = [];
    
    public function building(){
        return $this->belongsTo(Building::class);
    }
}

My Controller:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Apartment;
use App\Building; 

public function index()
{
    $apartment = Apartment::with('building')->get();
    return $apartment->building;
}

Error Message : Property [building] does not exist on this collection instance.

I would like to get result like that :

Building 1
   Apartment A
   Apartment b

Building 2
   Apartment A

Apartment b

Upvotes: 1

Views: 1166

Answers (1)

MrEduar
MrEduar

Reputation: 1931

The problem is that the get method gets an apartment collection should only get an apartment and then get the building from it.

public function index()
{
    $apartment = Apartment::with('building')->first();
    return $apartment->building;
}

The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP stdClass object. You may access each column's value by accessing the column as a property of the object:

$apartaments = Apartment::with('building')->get();

foreach ($apartments as $apartament) {
    echo $apartament->building;
}

Upvotes: 1

Related Questions