How to get the name of user through relations in Laravel - php

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);
}

Related

How do i calculate and view total work_time for specific id in laravel?

I have two tables employes and attendances . What I want is to sum work_time for each employe id and show in my view.
employes Table
id
attendances Table
id
employe_id
work_time
I want to sum work_time column for specific employe id. I am new to laravel so how do I do that with laravel eloquent.
Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function employee(){return $this->hasMany(Attendance::class);}}
Attendance.php
class Attendance extends Model{use HasFactory;
protected$fillable['id','employe_id','attendence_date','clock_in','clock_out','work_time','attendence_status'];
public function employe()
{return $this->belongsTo('App\Models\employe', 'employe_id');}}
AttendanceController
public function attendance(){
$attendances = Employe::all();
$hour = Attendance::where('employe_id',1)->sum('work_time');
return view('pages.Attendance.hour', compact('attendances','hour')); }
hour.blade.php
```
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50"
style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
#foreach($attendances as $attendances)
<tr>
<td></td>
<td>{{ $attendances->employe_code }}</td>
<td>{{ $attendances->employe_name }}</td>
<td>Hour {{ $hour }} </td>
</tr>
#endforeach
</table>
Only for Laravel 8.12 and above, you can use withSum()
First of all, correct the relation name in Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function attendances(){ //<---- here
return $this->hasMany(Attendance::class);
}
}
Here is the controller
public function attendance(){
$attendances = Employe::query()->withSum('attendances', 'work_time')->get();
return view('pages.Attendance.hour', compact('attendances'));
}
And the blade (kept the variable name $attendances but you should change it to employees)
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50" style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
#foreach($attendances as $employe)
<tr>
<td></td>
<td>{{ $employe->employe_code }}</td>
<td>{{ $employe->employe_name }}</td>
<td>Hour {{ $employe->attendances_sum_work_time }} </td>
</tr>
#endforeach
</table>

Passing variable from index to controller using Laravel

I am new to using Laravel and I am currently trying to pass a variable from the index blade file to the controller in order to bring up all apparatus type fields associated with a specific apparatus code id.
I am able to access the apparatus type fields associated with the apparatus code id when I include a specific number which correlates to that apparatus code id (eg. inputting 2 brings up the apparatus type details for the apparatus code id 2, inputting 3 brings up the apparatus type details for the apparatus code id 3 etc).
However when I have tried to pass a variable relating to each individual apparatus code id using a for loop in the controller, the apparatus type loop appears to not be accessed and does not return any information. I will include snippets of my current code for clarity.
Any help or guidance with this issue would be greatly appreciated!
Controller file
public function index()
{
$apparatusCodes = ApparatusCodes::get();
foreach ($apparatusCodes as $apparatusCode){
$apparatusTypes = ApparatusTypes::where('apparatus_code_id', $apparatusCode->id)->get();
}
return view('apparatus_codes.index', compact('apparatusCodes', 'apparatusTypes'));
}
Index.blade file
<table id="datatable" class="stripe hover dt-responsive display nowrap" style="width:100%; padding-top: 1em; padding-bottom: 1em;">
<thead>
<tr>
<th>ID</th>
<th >Apparatus Code</th>
<th>Description</th>
<th>Rent</th>
<th></th>
</tr>
</thead>
<!--start of for loop-->
#foreach ($apparatusCodes as $apparatusCode)
<tbody>
<tr data-toggle="collapse" id="table{{ $apparatusCode->id}}" data-target=".table{{ $apparatusCode->id}}">
<td> {{ $apparatusCode->id}} </td>
<td>{{ $apparatusCode->apparatus_code}} </td>
<td> {{ $apparatusCode->description}}</td>
<td> {{ $apparatusCode->rent}}</td>
<td #click="isOpen = !isOpen" class="main-bg"><img class="mb-1 duration-300 h-6 w-6" :class="{'transform rotate-180' : isOpen}"
src="../img/Icon-arrow-dropdown-white.png" alt="arrow down">
</td>
<td><img class="mb-1 duration-300 h-6 w-6" :class="{'transform rotate-180' : isOpen}"
src="../img/edit-icon.svg" alt="Edit Icon">
</td>
</tr>
<tr x-show.transition.duration.300ms.origin.bottom="isOpen" x-cloak #click.away="isOpen = false" class="collapse table{{ $apparatusCode->id}}">
<td colspan="999">
<div>
<table id="datatable" class="table table-striped">
<thead>
<tr>
<th>Apparatus Code </th>
<th>Apparatus Type</th>
<th>Compensation </th>
<th>Created On </th>
<th>Created By </th>
<th></th>
#foreach ($apparatusTypes as $apparatusType)
</thead>
<tbody>
<tr>
<td>{{ $apparatusCode->apparatus_code}}</td>
<td>{{ $apparatusType->apparatus_type }}</td>
<td>{{ $apparatusType->compensation }}</td>
<td>{{ $apparatusType->created_at }}</td>
<td>{{ $apparatusType->users->name}}</td>
<td> <button type="button" class="btn btn-default btn-edit js-edit"><img class="mb-1 duration-300 ml-4 inset-0 h-6 w-6" src="/../../img/Icon-edit-gray.png" alt="edit"></button></td>
</tr>
#endforeach
</table>
</tr>
</tr>
</td>
</tbody>
#endforeach
</table>
If you have the relationships setup you could eager load the ApparatusTypes for each ApparatusCode:
$apparatusCodes = ApparatusCodes::with('appartusTypes')->get();
Then in the view you could iterate the appartusTypes of each ApparatusCode:
#foreach ($apparatusCodes as $apparatusCode)
...
#foreach ($apparatusCode->apparatusTypes as $type)
...
#endforeach
...
#endforeach
Without using the relationships you could get all the ApparatusTypes for the ApparatusCodes and then group them by apparatus_code_id:
$codes = ApparatusCodes::get();
$types = ApparatusTypes::whereIn('apparatus_code_id', $codes->pluck('id'))
->get()
->groupBy('apparatus_code_id');
Then in the view you could iterate the group that corresponds to the current Code's apparatus_code_id:
#foreach ($codes as $code)
...
#foreach ($types->get($code->id, []) as $type)
...
#endforeach
...
#endforeach
Laravel 8.x Docs - Eloquent - Relationships - Eeager Loading with
Laravel 8.x Docs - Collections - Available Methods - pluck
Laravel 8.x Docs - Collections - Available Methods - groupBy

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>

How to show 2 tables data in 1 view using laravel?

There is two tables (one is Users and second is Branches). I want to show the Branch with its Branch Admin Name.And the branch Admin info is save in users table. There is an error When i am trying to show the data of Two table in one view. Tell me How i manage this issue.
View:
<div class="branches col-xs-12 col-sm-12 col-md-9 col-lg-9">
<input type="text" class="pull-right form-control search" placeholder="Search">
<div class="spaces"></div>
<table class="table table-bordered">
<thead>
<tr>
<th>
BranchName
</th>
<th>
BranchAdmin
</th>
<th>
Email
</th>
<th>
Contact
</th>
<th>
Location
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
#foreach($branch as $brnch)
<tr class="branchies-row">
<td>
{{$brnch->branch_name}}
</td>
#foreach($user as $users)
<td>
{{$users->name}}
</td>
#endforeach
<td>
{{$brnch->email}}
</td>
<td>
{{$brnch->contact}}
</td>
<td>
{{$brnch->address}}
</td>
<td>
<a data-id="{{$brnch->id}}" class="delete-branch">Delete</a> /
Edit
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Controller:
public function getBranchinfo(){
$user = User::where('type', '=', 'BranchAdmin');
$branch = Branch::all();
return view('Branch.branchinfo')->with('branch',$branch)->with('user', $user);
}
Model:
public function branch(){
return $this->hasOne('App\Branch', 'user_id', 'id');
}
We can use query builder - Join - for that :
$branches = DB::table('Branches')
->join('users', 'users.id', '=', 'Branches.user_id')
->where('users.type', '=', 'BranchAdmin')
->get();
and this should give you the data you need.
You have to make the relationship in branch model:
public function user(){
return $this->belongsTo('App\User');
}
Then in blade file you get branch admin name as:
#foreach($branch as $brnch)
<tr class="branchies-row">
<td>{{ $brnch->user->branchadmincloumn }}</td>
</tr>
#endforeach
branchadmincloumn is the cloumn name from your users table where your branch admin name is saving. So change branchadmincloumn to your desired column name.
Hope it helps..

Categories