Andy
Andy

Reputation: 111

How to grab data from another table with this relationship setup?

I have four tables

City

  id
  city
  state_id

State

 id
 name

City_Vendor

 id
 vendor_id
 city_id

Vendor

 id 
 name

Now if I do something like this I get the cities and the state_id but not the state name

   Vendor::with('cities')->get();

This is what I did to get the states in my view which is not ideal..

              <?php foreach($vendor['cities'] as $state): ?>
                  @if($state['state_id'] == $city['state_id'])
                    {{$state['state']['state']}}
                    <?php break; ?>
                  @endif
              <?php endforeach;?>

I would like to get states name too not just the state_id. What would would be the best way to go about doing this?

Upvotes: 0

Views: 40

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

Assuming you have correct relationship, it should be rather something like that:

@foreach ($vendor->cities as $city)
  {{ $vendor->city->city}}, {{$vendor->city->state->name}}
@endforeach

In above code you display for one vendor city with state name

and instead of:

Vendor::with('cities')->get();

you should rather use:

Vendor::with('cities.state')->get();

Upvotes: 1

Related Questions