How to access laravel collection in a foreach loop in blade template?

12,038

Solution 1

You've not defined your relationships properly. App\User should have this defined in the model:

public function pages()
{
    // have to specify the key name is author, not user_id
    return $this->hasMany("App\Page", "author");
}

And then in the App\Page model you have this:

public function pageauthor()
{
    // have to specify the key name is author, not user_id
    return $this->belongsTo("App\User", "author");
}

Then in your Blade template you just reference $page->author->name:

@foreach ($pages as $page)
            <tr>
              <th>{{ $page->id }}</th>
              <th>{{ $page->title }}</th>
              <th>{{ $page->pageauthor->name }}</th>
...

Solution 2

You can use foreach loop in controller to access its attributes.

like this

$users = \App\user::where('id', $page->author)->get('name');

$data = [];

foreach( $users as $user ){
        $data['name'] = $user['name'];       
   }

After that pass the $data array in your blade file and access name by $data['name'];

Solution 3

Something like this should help you

Your controller

$pages = \App\page::all();
foreach ($pages as $page) {
    $user = \App\user::find($page->author)->pluck('name');
    if(isset($user)){
      $page['user_name'] = $user->name;
    } else {
       $page['user_name'] = 'N/A';
     }
}
return view('admin.pages', compact('pages'));

Your view

    @foreach ($pages as $page)
            <tr>
              <th>{{ $page->id }}</th>
              <th>{{ $page->title }}</th>
              <th>{{ $page->user_name) }}</th>
              @if($page->status = 'ACTIVE')
              <th><span class="label label-success">{{ $page->status }} 
    </span></th>
              @elseif($page->status = 'DRAFT')
              <th><span class="label label-warning">{{ $page->status }} 
</span></th>
               @endif
              <th>{{ $page->Actions }}</th>
            </tr>
            @endforeach

How is the code different from your current code

1) it writes the name of the user in the main collection itself ($pages) thereby allowing you to worry about looping through only one collection in your view

2) it's uses laravel's find() since a page can have only author (I assume) (Note : find() works based off of your primary key , in this case it will be searching through id column which is the most common primary key column)

3) it uses pluck()

Share:
12,038

Related videos on Youtube

Anonymous
Author by

Anonymous

Updated on June 04, 2022

Comments

  • Anonymous
    Anonymous almost 2 years

    I want to get the user name details from the table Users with the author ids from the table Pages. For this, I have made a foreach loop and added the data to users array.

    This gets the data but its not properly formatted to use in blade template. Below is the code :

    $pages = \App\page::all();
        $users = array();
        foreach ($pages as $page) {
            $user = \App\user::where('id', $page->author)->get('name');
            $users[] = $user;
        }       
        dd($users);
        return view('admin.pages', compact('pages', 'users'));
    

    I have dumped the results with dd($users) method and got this: Image

    I am using this code in the blade template to retrieve but getting blank white space at the $users[$loop->index]->get('name') place.

    @foreach ($pages as $page)
                <tr>
                  <th>{{ $page->id }}</th>
                  <th>{{ $page->title }}</th>
                  <th>{{ $users[$loop->index]->get('name') }}</th>
                  @if($page->status = 'ACTIVE')
                  <th><span class="label label-success">{{ $page->status }} </span></th>
                  @elseif($page->status = 'DRAFT')
                  <th><span class="label label-warning">{{ $page->status }} </span></th>
                  @endif
                  <th>{{ $page->Actions }}</th>
                </tr>
                @endforeach
    
    • Dev Man
      Dev Man almost 5 years
      Set assoc arrays whilst in the foreach loop
    • Anonymous
      Anonymous almost 5 years
      Can you explain me little more
    • Dev Man
      Dev Man almost 5 years
      Check answer, I've also included an explanation of how the answer code is different from your current code
    • miken32
      miken32 almost 5 years
      You should not edit your question to indicate that it's solved. Marking an answer accepted will provide that information to future visitors.
    • Anonymous
      Anonymous almost 5 years
      Yeah but @ImmortalDude method was correct but not given me the expected result, So I did that. Your Answer is perfect so I marked your answer as accepted.
  • Anonymous
    Anonymous almost 5 years
    But We have to first loop users table with the author ids from pages table.
  • Anonymous
    Anonymous almost 5 years
    I have tried your code but it says $data vaiable is not defined in controller
  • fahim152
    fahim152 almost 5 years
    did u pass $data in the blade ? like this : return view('admin.pages', compact('pages', 'users', 'data'));
  • Anonymous
    Anonymous almost 5 years
    Getting This error Property [name] does not exist on this collection instance. . name coloumn is there is the users table for sure.
  • Anonymous
    Anonymous almost 5 years
    yeah, Passed But before that Getting error in the controller page first saying $data variable not defined.
  • Dev Man
    Dev Man almost 5 years
    Hmm then is seems that some of your users cannot be found
  • Anonymous
    Anonymous almost 5 years
    Every page have an author and evry author has name . Check users table --> https://imgur.com/2OP5nYt and pages table --> https://imgur.com/v4YVzTY
  • miken32
    miken32 almost 5 years
    If you expect to be able to change $pages in your loop you need to be passing it by reference. Your loop does nothing right now.
  • Anonymous
    Anonymous almost 5 years
    It was solved by changing this $user = \App\User::find($page->author)->pluck('name'); to $user = \App\User::where('id', $page->author)->get('name'); and this $page['user_name'] = $user->name; to $page['user_name'] = $user[0]->name;
  • fahim152
    fahim152 almost 5 years
    I've edited the code section. please check. define $data= []; before the foreach
  • Dev Man
    Dev Man almost 5 years
    @miken32 the code I've suggested is based off of code I have personally used in daily developement, and I am certain it works, see the OP comment on the answer, it seems something is wrong with finding the value from users table
  • miken32
    miken32 almost 5 years
    The only thing it does is add an element to $page which is an ephemeral variable that disappears with the next iteration. It affects nothing. What you want is foreach ($pages as &$page)
  • Dev Man
    Dev Man almost 5 years
    @Anonymous is the author field in page an integer??
  • Anonymous
    Anonymous almost 5 years
    No it was string. I forgot to make it an integer.Is it any problem If I use this way.
  • Anonymous
    Anonymous almost 5 years
    I will Try using relationships.
  • Dev Man
    Dev Man almost 5 years
    @Anonymous that is the reason why the suggested answer didn't work, IDs should really be integers
  • Dev Man
    Dev Man almost 5 years
    @miken32 no it doesn't disappear with the next iteration, the reason why the answer code didn't work is because the OP had set the author field as a string , find doesn't work with non integers as it searches the primary key column which is an integer
  • miken32
    miken32 almost 5 years
    Relationships are the building blocks of Laravel, the app should be planned around them. I can tell by your database column names that this was not the case.
  • Dev Man
    Dev Man almost 5 years
    @miken32 thank you for your time, it is very much appreciated
  • Anonymous
    Anonymous almost 5 years
    I am getting this error Trying to get property of non-object (View: H:\laravel\work\resources\views\admin\pages.blade.php)
  • miken32
    miken32 almost 5 years
    I've told you how it should be done, but I can't help you debug your whole app. Do some dumping, do some reading. laravel.com/docs/5.8/eloquent-relationships#one-to-many
  • Anonymous
    Anonymous almost 5 years
    Yeah, I understand. Thanks @miken32
  • Anonymous
    Anonymous almost 5 years
    Just Tell me In which relationship my case comes. I have pages and author ids in the pages table where with these author Ids I can fetch their name from users table.
  • miken32
    miken32 almost 5 years
    In your table pages you have a column called author that is a number, and in your table users you have a id column that is also a number? The author of the page is an id of a user? If users primary key is something other than id then code needs to be changed.
  • Anonymous
    Anonymous almost 5 years
    Yes, author of the page is an id of user.
  • miken32
    miken32 almost 5 years
    There might be a conflict between the relationship name and the database column name. I'll make a small edit.
  • miken32
    miken32 almost 5 years
    Glad to help. If you're just starting out on this, you will make your life a lot easier by reworking your database to fit with Laravel conventions. laravel.com/docs/5.8/eloquent#eloquent-model-conventions
  • M a m a D
    M a m a D about 2 years
    very bad coding. Never use find inside a for loop. instead try to use whereIn, in this way you will query on database just 1 time not multiple times
  • Dev Man
    Dev Man about 2 years
    @MamaD true, should be using relationship, but this is something the OP wanted, may be some restrictions on his end