Laravel displaying many to many relationship items

Viewed 3372

I have set up a many to many relationship in Laravel and have the database table populated with data. The relationship setup looks like this...

users.php
---------
   public function houses()
    {
        return $this->belongsToMany('App\House')
        ->withTimestamps();
    }

house.php
---------
public function users()
    {
        return $this->belongsToMany('App\User')
        ->withTimestamps();
    }

In my /house/show.blade.php I am trying to display the saved connections like this...

$houses = House::with('App\User')->all();

foreach ($houses as $house) {
    echo 'Found House';
}

It is giving me an error saying that $houses can not be found. Where am I going wrong?

2 Answers

You should indicate the relationship in the with method like this :

$houses = House::with('users')->get();

And one more thing it's better to get houses in the controller and pass them to the view :

$houses = House::with('users')->get();
return view('someView')->withHouses($houses);

And in the view do it like this :

@foreach ($houses as $house)
    {{ $house->addres }}
@endforeach

To get only the houses taht has the users try this :

$houses = House::has('users')->get();

And to add some conditions on the users you can do it like this :

$houses = House::whereHas('users', function ($query) {
    $query->where('name', 'some user name'); // to add some conditions on the user :)
})->get(); 

You should try this:

$houses = House::with('users')->get();

foreach ($houses as $house) {
    echo 'Found House';
}

OR

In controller:

use House;

$houses = House::with('users')->get();
return view('someView',compact('houses'));

In Blade file:

@foreach ($houses as $house)
    {{ $house->name }}
@endforeach
Related