1

I want to display information to the user showing what communities they are in, inside of the view. Here is the controller method where I'm getting the data:

public function index()
{
    $communities = array();

    $usersCommunities = CommunityMemberList::where('user_id', Auth::user()->id)->get();

    foreach ($usersCommunities as $community) {
        $communitiesInfo = Community::where('id', $community->community_id)->get();

        array_push($communities, $communitiesInfo);
    }

    return view('home', compact('communities', 'badges'));
}

$userCommunities gets all of the community ids that the user has from a table. Then I want to get the all of the communities information from another table using the community_id.

So basically there are 2 tables:

  • community_member_list which has a community_id and a user_id column
  • communities which has irrelevant information about a community

The community_id from the first table will correspond to the id in the second table.

This works, it gets all of the communities information data that the user is in and returns this data after being pushed into the $communities array from the foreach loop:

array:2 [▼
  0 => Collection {#236 ▼
    #items: array:1 [▼
      0 => Community {#249 ▼
        #connection: "mysql"
        #table: "communities"
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:10 [▶]
        #original: array:10 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
        #guarded: array:1 [▶]
      }
    ]
  }
  1 => Collection {#250 ▼
    #items: array:1 [▼
      0 => Community {#251 ▼
        #connection: "mysql"
        #table: "communities"
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:10 [▶]
        #original: array:10 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
        #guarded: array:1 [▶]
      }
    ]
  }
]

However, if I return this to the view I cannot access the specific data values such as a community name or description. And if I try using something like array_pop or array_shift, it only returns either the last community array or the first community array.

(This is the view file for reference:)

@if(!empty($communities))
    @foreach($communities as $community)
        <div class="card communityCard bg-dark col-md-3">
            <img class="communityIcon" src="/images/communityIcons/{{$community->icon_path}}">

            <div class="communityInformation">
                <span class="communityTitle">{{$community->name}}</span>
                <span class="userCount"><i class="fas fa-users"></i> {{$community->user_count}}</span>
            </div>

            <button class="btn launchCadBtn btn-primary  btn-sm">Launch CAD</button>
      </div>
    @endforeach
@else
    <span class="subTitle">You are not in any Communities. To join a Community, press the <i class="fas fa-plus-circle"></i> button and enter a Community ID</span>
@endif

Thanks in advance ;)

1
  • You are doing many queries.You can do it with 2 query. Try my solution Commented Mar 10, 2019 at 15:00

2 Answers 2

2

Just return the values as follows in your controller :

public function index()
{
    $communities = array();

    $usersCommunities = CommunityMemberList::where('user_id', Auth::user()->id)->get();

    foreach ($usersCommunities as $community) {
        $communitiesInfo = Community::where('id', $community->community_id)->first();

        array_push($communities, $communitiesInfo);
    }

    return view('home', ['communities' => $communities, 'badges' => $badges]);
}

And the view should work fine. The problem is that you're trying to access the $communities as a collection but it's actually an array of communities, which itself was a collection of collections due to get() and badges list.

Sign up to request clarification or add additional context in comments.

4 Comments

Already tried that and it's returning this error from the foreach loop in the view; Property [icon_path] does not exist on this collection instance. (View: /Users/EthanPhelps/Websites/cadispatch/resources/views/home.blade.php). icon_path is a column in the database but because it's nested inside of another object you can't just retrieve it with the foreach loop.
There is a 'hack' way of making it work, and that's by putting a foreach loop inside of a foreach loop. But this isn't a clean method.
That is because $communitiesInfo = Community::where('id', $community->community_id)->get(); returns a collection. So basically $communities is a collection of collection, whereas first() returns the model. Try my edit.
Yes, I was under the impression that first() would only get 1. But I was mistaken! Thank you :)
2

Try this solution it is only 2 query

public function index()
{
    $communitiesIds = CommunityMemberList::where('user_id', Auth::user()->id)->pluck('community_id');
    $communities = Community::whereIn('id', $communitiesIds)->get();

    return view('home', ['communities' => $communities, 'badges' => $badges]);
}

1 Comment

Thank you, it works! I thought it was a bit overkill :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.