Laravel: How to display the value of other table in a loop? - php

So, I have this code which is printing the various topics/threads started by the user.
It is looping over the Posts table that contains data related to posts.
In User column, it will display user_id. But I want to access User table and display the user_name column matching that user_id. How to do this?
<table border="2">
<tr>
<th>Topic</th>
<th>User</th>
<th>Replies</th>
<th>Views</th>
<th>Last Update</th>
</tr>
#foreach($topics as $topic)
<tr>
<td>{{$topic->topic_title}}</td>
<td>{{$topic->id}}</td>
<td>0</td>
<td>0</td>
<td>{{$topic->updated_at}}</td>
</tr>
#endforeach
</table>
Controller's Code:
public function show($id)
{
$topics = Topic::where('board_id', $id)->get();
return view('boards.show')->with('topics', $topics);
}

In controller eager load user model:
$topics = Topic::where('board_id', $id)->with('user')->get();
In view:
<td>{{ $topic->user->user_name }}</td>
I assume you already have the user relationship defined in Topic model:
public function user()
{
return $this->belongsTo(User::class);
}

you can try something like this:
#foreach($topics as $topic)
#php $user = DB::table('User')->where('id', $topic->id)->first(); #endphp;
<tr>
<td>{{$topic->topic_title}}</td>
<td>{{ $user }}</td>
<td>0</td>
<td>0</td>
<td>{{$topic->updated_at}}</td>
</tr>
#endforeach

In your Post model
public function user(){
$this->belongsTo(User::class);
}
In your blade {{$topic->user->name}}
<table border="2">
<tr>
<th>Topic</th>
<th>User</th>
<th>Replies</th>
<th>Views</th>
<th>Last Update</th>
</tr>
#foreach($topics as $topic)
<tr>
<td>{{$topic->topic_title}}</td>
<td>{{$topic->user->name}}</td>
<td>0</td>
<td>0</td>
<td>{{$topic->updated_at}}</td>
</tr>
#endforeach

You need to define relation in models first like this:
class User extends Model
{
public function post()
{
return $this->hasMany("App\Post");
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo("App\User");
}
}
then in the loop on the view side you can access user's data like this:
#foreach($topics as $topic)
<tr>
<td>{{$topic->user->name}}</td>
</tr>
#endforeach
You do not need to use "with" function in this case. you only need to fetch topics, pass them on to view, iterate through and you get the user's data

Related

Barryvdh/laravel-domPDF returning Attempt to read property "name" on bool

Im using Laravel 8 with PHP 8 as well as barryvdh/laravel-domPDF. I have a crud that displays employee information and you can print out their payslips. When i dont pass through the $id it works correctly and prints all the employees information however when i do it returns the error:
Attempt to read property "name" on bool
This is my route:
Route::get('/print/{id}', ['App\Http\Livewire\EmployeesTable', 'print'])->name('livewire.employees-table.print');
This is my model function
public function print($id){
$employees = Employees::find($id);
$teams= Team::all();
$pdf = PDF::loadView('employees.payslip', compact('teams', 'employees'));
return $pdf->download('invoice.pdf');
}
This is my user relationship:
public function employees(){
return $this->hasMany(Employees::class);
}
This is my employees relationship:
public function user(){
return $this->belongsTo(User::class);
}
.
<thead>
#foreach ($employees as $employee)
<tr>
<td>
{{$employee->name}} {{$employee->surname}}
{{$employee->phone}}
{{$employee->role}}
</td>
</tr>
#endforeach
</thead>
<thead>
#foreach ($teams as $team)
<tr>
<td>
{{$team->companyName}}
{{$team->street}}
{{$team->compound}}
{$team->suburb}}
{$team->phone}}
</td>
</tr>
#endforeach
</thead>
</table>
I think $employees return empty result so better check before looping
#if(isset($employees)&&count((array)$employees))
#foreach ($employees as $employee)
<tr>
<td>
{{$employee->name}} {{$employee->surname}}
{{$employee->phone}}
{{$employee->role}}
</td>
</tr>
#endforeach
#endif

How to get the name of user through relations in Laravel

I want to implement simple teaming option to my app. I have theese tables:
users/teams /team_members/
-----/---------/------------/
id /id /id /
name /user_id /user_id /
... /... /team_id /
I have 3 models where I have defined relations:
User model:
public function teams() {
return $this->hasOne(Team::class);
}
public function teamMembers() {
return $this->hasManyThrough(Team::class, TeamMembers::class);
}
Team model:
public function user() {
return $this->belongsTo(User::class);
}
public function members() {
return $this->hasMany(TeamMember::class);
}
TeamMember model:
public function user() {
return $this->belongsTo(User::class);
}
User can only create one team, but join many teams. The problem I have is with displaying data in the frontend.
This is the query I make in the controller:
public function index(User $user) {
$teams = Team::where('user_id', auth()->user()->id )->with('members')->get();
return view('teams.index')->with('teams', $teams);
}
I have a table with the members of the current autheticated user team. I want to display the names if each member but the only thing i can do is $team->member->id and I get the ids of the users but I want to get their names too. I can do it with simple query but I dont want to make new query for every row.
This is the blade file:
#if ( $teams->count() > 0 )
#foreach ($teams as $team)
<table class="table table-striped table-sm table-responsive-lg">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Members</th>
<th scope="col">Created</th>
<th scope="col" colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td>{{$team->name}}</td>
<td>{{ $team->members->count('members')}} {{ Str::plural('member', $team->id) }}</td>
<td>{{ $team->created_at->diffForHumans() }}</td>
<td>
Edit
</td>
<td>
<form action="" method="POST">
#method('DELETE')
#csrf
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
<br>
<h5>Team members:</h5>
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Added</th>
</tr>
</thead>
<tbody>
#foreach ($team->members as $member)
<tr>
<td>{{ $member->user->name }}</td>
<td>{{ $member->created_at->diffForHumans() }}</td>
</tr>
#endforeach
</tbody>
</table>
#endforeach
#else
<div class="container">
<h2>You do not own a team</h2>
<p class="lead text-muted">You can create your own team or join the team of other user.</p>
<p>
Create team
Join team
</p>
</div>
#endif
When I changed $team->member->id with $member->user->name it worked. It shows the names of the users but I get N+1 queries alert and I don't know how to fix it (i tried different queries and relations but it didnt work):
You are accessing the user relationship from each member. So lets eager load that relationship as well.
public function index(User $user)
{
$teams = Team::where('user_id', auth()->user()->id )->with('members.user')->get();
return view('teams.index')->with('teams', $teams);
}

Laravel - Counting a collection of models

I'm trying to get the count of different models and list them by company.
I have a collection of different models.
public function listAllRequets()
{
$requests = collect();
$terms = Termination::with('user.company')->where('default_status', 2)->get();
$deacs = LoaDeactivation::with('user.company')->where('manager_status', 2)->get();
$reacs = LoaReactivation::with('user.company')->where('manager_status', 2)->get();
// Use push() to collect them all in one collection
foreach ($terms as $term)
$requests->push($term);
foreach ($deacs as $deac)
$requests->push($deac);
foreach ($reacs as $reac)
$requests->push($reac);
return $requests;
}
In my index function I'm adding them to $requests.
To get the list of companies I'm grouping them using the groupBy() method.
public function index()
{
$requests = $this->listAllRequets();
$requestCompanies = $requests->groupBy(function($requests) {
return $requests->user->company->company_acronym;
});
In my view I have this:
<table class="table table-sm">
<thead class="thead-light">
<tr>
<th>Company</th>
<th class="text-center">Terms</th>
<th class="text-center">Deacs</th>
<th class="text-center">Reacs</th>
</tr>
</thead>
<tbody>
#foreach ($requestCompanies as $company => $requests)
<tr>
<td class="pt-3"><strong>{{ $company }}</strong></td>
#foreach ($requests as $request)
<td class="text-center">{{ $request-> }}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
I need a way to get the count of each model by company.
My companies list out as expected but I'm not sure how to get the correct model count.
If you have relationships among your company and each request model (Termination, LoaDeactivation, LoaReactivation), wouldn't be easier to do that with a query at database level?
That seems a nice use case for with count method that eloquent provides:
Assuming the relations in the company model are called terminations, deactivations and reactivations, you could do:
public function index()
{
$companies = Company::withCount('terminations','deactivations','reactivations')->get();
// here pass $companies array to your view
}
Then in your view you can access the count for each type on each company:
<table class="table table-sm">
<thead class="thead-light">
<tr>
<th>Company</th>
<th class="text-center">Terms</th>
<th class="text-center">Deacs</th>
<th class="text-center">Reacs</th>
</tr>
</thead>
<tbody>
#foreach ($companies as $company)
<tr>
<td class="pt-3"><strong>{{ $company->name }}</strong></td>
<td class="text-center">{{ $company->terminations_count }}</td>
<td class="text-center">{{ $company->deactivations_count }}</td>
<td class="text-center">{{ $company->reactivations_count }}</td>
</tr>
#endforeach
</tbody>
</table>

How can I rearrange this table to another away laravel eloquent relation

I used laravel hasmany relationship in my user model. I just want to convert my table like below (row to column):
To:
Here is my User model:
public function meal(){
return $this->hasMany(Meal::class);
}
My controller:
public function index()
{
$members = User::all();
return view('admin.meal')->with([
'members' => $members,
]);
}
and #blade
<table class="table table-striped #if(count($members)>7) table-responsive #endif ">
<thead>
<tr class="text-uppercase">
{{--<th class="font-w700">Date</th>--}}
#foreach($members as $member)
<th class="font-w700">{{str_limit($member->fname,5,'...')}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($members as $member)
<tr>
#foreach($member->meal as $meal)
<td><span class="font-w600">{{$meal->user_id}}</span></td>
#endforeach
</tr>
#endforeach
</tbody>
</table>

Displaying additional attribute in table - Laravel

My pivot table admin_user with additional attribute item_no. I am finding it hard to retrieve the additional attribute into my html table.
PS: i tried $admin->pivot->item_no in my table but i get an error trying to get a non-object
Admin
public function users()
{
return $this->belongsToMany('App\User')->withPivot('item_no')
->withTimestamps();
}
admin_food
admin_id
user_id
item_no
Controller
public function index()
{
$admins = Admin::where('id',1)->get();
return view('index',compact('admins'));
}
HTML
<table class="table" id="table">
<thead>
<tr>
<th>Order No#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
#foreach($admins as $admin)
<tr >
<td>{{$admin->name}}</td>
</tr>
#endforeach
</tbody>
</table>
You access the item_id by access the pivot property of the user/related model.
Your controller is returning a collection that has only one admin.
$admins = Admin::where('id',1)->get();
admins will be a collection of 1 admin that has id = 1.
if this was on purpose, then you can access the item_id for every user related to this admin by this code:
#foreach($admins as $admin)
#foreach($admin->users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->pivot->item_id}}</td>
</tr>
#endforeach
#endforeach
To simplify:
$admin = Amdin::first();
$item_id = $admin->users()->first()->pivot->item_id

Categories