How to access laravel collection in a foreach loop in blade template?
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()
Related videos on Youtube
Anonymous
Updated on June 04, 2022Comments
-
Anonymous almost 2 years
I want to get the user name details from the table
Users
with the authorid
s from the tablePages
. For this, I have made aforeach
loop and added the data tousers
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: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 almost 5 yearsSet assoc arrays whilst in the foreach loop
-
Anonymous almost 5 yearsCan you explain me little more
-
Dev Man almost 5 yearsCheck answer, I've also included an explanation of how the answer code is different from your current code
-
miken32 almost 5 yearsYou should not edit your question to indicate that it's solved. Marking an answer accepted will provide that information to future visitors.
-
Anonymous almost 5 yearsYeah 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 almost 5 yearsBut We have to first loop users table with the author ids from pages table.
-
Anonymous almost 5 yearsI have tried your code but it says $data vaiable is not defined in controller
-
fahim152 almost 5 yearsdid u pass $data in the blade ? like this : return view('admin.pages', compact('pages', 'users', 'data'));
-
Anonymous almost 5 yearsGetting This error
Property [name] does not exist on this collection instance.
. name coloumn is there is the users table for sure. -
Anonymous almost 5 yearsyeah, Passed But before that Getting error in the controller page first saying $data variable not defined.
-
Dev Man almost 5 yearsHmm then is seems that some of your users cannot be found
-
Anonymous almost 5 yearsEvery page have an author and evry author has name . Check users table -->
https://imgur.com/2OP5nYt
and pages table -->https://imgur.com/v4YVzTY
-
miken32 almost 5 yearsIf 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 almost 5 yearsIt 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 almost 5 yearsI've edited the code section. please check. define $data= []; before the foreach
-
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 almost 5 yearsThe 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 isforeach ($pages as &$page)
-
Dev Man almost 5 years@Anonymous is the author field in page an integer??
-
Anonymous almost 5 yearsNo it was string. I forgot to make it an integer.Is it any problem If I use this way.
-
Anonymous almost 5 yearsI will Try using relationships.
-
Dev Man almost 5 years@Anonymous that is the reason why the suggested answer didn't work, IDs should really be integers
-
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 almost 5 yearsRelationships 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 almost 5 years@miken32 thank you for your time, it is very much appreciated
-
Anonymous almost 5 yearsI am getting this error
Trying to get property of non-object (View: H:\laravel\work\resources\views\admin\pages.blade.php)
-
miken32 almost 5 yearsI'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 almost 5 yearsYeah, I understand. Thanks @miken32
-
Anonymous almost 5 yearsJust 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 almost 5 yearsIn your table
pages
you have a column calledauthor
that is a number, and in your tableusers
you have aid
column that is also a number? Theauthor
of the page is anid
of a user? Ifusers
primary key is something other thanid
then code needs to be changed. -
Anonymous almost 5 yearsYes, author of the page is an
id
of user. -
miken32 almost 5 yearsThere might be a conflict between the relationship name and the database column name. I'll make a small edit.
-
miken32 almost 5 yearsGlad 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 about 2 yearsvery bad coding. Never use
find
inside a for loop. instead try to usewhereIn
, in this way you will query on database just 1 time not multiple times -
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