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
4
  • What is the table look ? The syntax looks good Commented Dec 10, 2015 at 21:15
  • 1
    I believe you just want to wrap your <tr>...</tr> contents in something like this: @if ($agent->user_type_id === 2) <tr> ... </tr> @endif - see the Laravel Templates docs section titled If Statements Commented Dec 10, 2015 at 21:16
  • thank you.. it worked :) @cale_b Commented Dec 10, 2015 at 21:22
  • Can @cale_b's answer be accepted, Noob? Answer acceptance is not mandatory on Stack Overflow, but it is encouraged, because it is helpful both to the answerer and to other readers. Commented Jan 26, 2018 at 0:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Nice. Didn't know about where being available at this level. Cool!

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.