Noob Coder
Noob Coder

Reputation: 2896

Using foreach in Laravel 5.1

I'm new in Laravel. I'm storing 3 types of user in my users table:

  1. admin : user_type_id = 1
  2. agent : user_type_id = 2
  3. farmer : user_type_id = 3

user_type_id column is in the users table.

In one of my Blade files, I want to only show the names of the agents. Here is my foreach loop, which is importing all 3 types of the user (it's showing the names of admins, agents and farmers).

@foreach($farmerPoint->user as $agent)
<tr>
  <td>{{ $agent->name }}</td>
  <td>{{ $agent->phone }}</td>
</tr>
@endforeach

Upvotes: 1

Views: 470

Answers (2)

Steve Bauman
Steve Bauman

Reputation: 8678

You can use a simple blade @if() statement like so:

@foreach($farmerPoint->user as $agent)
    @if ($agent->user_type_id === 2)
    <tr>
        <td>{{ $agent->name }}</td>
        <td>{{ $agent->phone }}</td>

    </tr>
    @endif
@endforeach

Or you can use a collection where() since all eager / lazy loaded relations are returned in collections:

http://laravel.com/docs/5.1/collections#method-where

@foreach($farmerPoint->user->where('user_type_id', 2) as $agent)
     <tr>
        <td>{{ $agent->name }}</td>
        <td>{{ $agent->phone }}</td>

    </tr>
@endforeach

Upvotes: 1

random_user_name
random_user_name

Reputation: 26160

This is probably more of a logic issue than a Laravel issue. NOTE that I would suggest you limit the $agents instead using your query (where) rather than this way, BUT:

@foreach($farmerPoint->user as $agent)
    @if ($agent->user_type_id === 2) 
            <tr>
                  <td>{{ $agent->name }}</td>
                  <td>{{ $agent->phone }}</td>

            </tr>
    @endif
@endforeach

Upvotes: 1

Related Questions