I want to count total yes against an id in a particular row not a column - laravel

I want to sum total yes in a row like following
id
user_id
eligible
asset
requirement
1
1
yes
no
yes
2
1
yes
yes
yes
3
2
no
yes
no
Result should be following:
user_id
yes_count
1
5
2
1

I consider that table as Items.
User model
public function items()
{
return $this->hasMany(Item::class);
}
Controller
$users = User::withCount([
'items as items_eligible_yes_count' => fn($q) => $q->where('eligible', 'yes'),
'items as items_asset_yes_count' => fn($q) => $q->where('asset', 'yes'),
'items as items_requirement_yes_count' => fn($q) => $q->where('requirement', 'yes'),
])
->get();
View
<table>
<thead>
<tr>
<th>user_id</th>
<th>yes_count</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->items_eligible_yes_count + $user->items_asset_yes_count + $user->items_requirement_yes_count }}</td>
</tr>
#endforeach
</tbody>
</table>

Related

Value correlation from multiple tables in laravel

I have two tables. One employees and one timesheets
I would like to have correct name at the result but different ID. If you see the result I have the same name everywhere.
How can make the code to fixed my challenge?
Thank you.
In controller I have this code
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->select('*')->orderBy('created_at','DESC')->get();
foreach ($timesheets as $employee) {
$emp = ['identification' => $employee->identification];
$oneemployee = Employees::where($emp)->select('*')->orderBy('created_at','DESC')->get();
}
return view('contractor.employees.timesheets', compact('timesheets', 'oneemployee'));
and in blade I have
#foreach ($timesheets as $row1)
<tr>
<td>#</td>
#foreach ($oneemployee as $row2)
<td>{{ $row2->fname}}</td>
<td>{{ $row2->lname}}</td>
#endforeach
<td>{{ $row1->identification}}</td>
<td>{{ $row1->week}}</td>
<td>{{ $row1->year}}</td>
</tr>
#endforeach
According to your commit, I suggest the following solution
If you want dispay timesheet with employees you can use eager loading.
For example:
In your controller:
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->with("employees")->select('*')->orderBy('created_at','DESC')->get();
return view('contractor.employees.timesheets', compact('timesheets'));
In your Timesheet model add hasOne relation to Employee:
public function employee(){
return $this->hasOne(Employee::class,'identification','identification')
}
And your view:
#foreach ($timesheets as $timesheet)
<tr>
<td>#</td>
<td>{{ $timesheet->employee->fname}}</td>
<td>{{ $timesheet->employee->lname}}</td>
<td>{{ $timesheet->identification}}</td>
<td>{{ $timesheet->week}}</td>
<td>{{ $timesheet->year}}</td>
</tr>
#endforeach

Laravel 7: Match two column dates with current date and show value depends on the condition

Leave:
id
user_id
start_date
end_date
1
2
2022-06-01
2022-06-03
Blade:
#foreach ($users as $row )
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $row->id }}</td>
<td>{{ $row->name }}</td>
<td>{{ $row->dpt->department }}</td>
#php
$today = Carbon\Carbon::now();
$leave = App\Leave::where('user_id', $row->id)->whereBetween('') <!-- incomplete -->
#endphp
<td>Leave Status</td>
</tr>
#endforeach
In this table, all user lists are shown. Here in the Leave Status column, it will show On Leave if the user is on leave today. I think I have to match today's date with start_date and end_date of the leave table and also match the user_id
What will be the eloquent query for this?
Example:
id
name
Leave Status
1
Jhon
Present
2
Doe
On Leave
3
Laura
On Leave
If you also have the relationships defined in the model you could load them with constraints in your controller:
$users = User::with(['leaves' => function ($query) {
$query->where('start_date', '>=', Carbon::now()))
->where('end_date', '<=', Carbon::now()));
}])->get();
This way you don't have to query in your blade templates and you can just check if count($row->leaves) > 0
have you try this:
\Carbon\Carbon::now()->between($row->leaves()->last()->start_date,$row->leaves()->last()->end_date) ? 'On Leave' : 'Present';

not able to show array in Table #foreach

I am new to Laravel and coding. Trying to show Month name (Array) in table but not able to do the same. I tried few things like "json_encode" but got error each time.
My controller code is
$months = array();
for ($i = 0; $i < 12; $i++) {
$timestamp = mktime(0, 0, 0, date('n') - $i, 1);
$months[date('n', $timestamp)] = date('M-Y', $timestamp);
}
Output is
array:12 [▼
3 => "Mar-2022"
2 => "Feb-2022"
1 => "Jan-2022"
12 => "Dec-2021"
11 => "Nov-2021"
10 => "Oct-2021"
9 => "Sep-2021"
8 => "Aug-2021"
7 => "Jul-2021"
6 => "Jun-2021"
5 => "May-2021"
4 => "Apr-2021"
]
View file
<table id="incometable" class="table m-0 table table-bordered table-hover table" data-order='[[ 0, "desc" ]]'>
<thead>
<tr>
<th align="center">Month</th>
<th>Milk Sale Amount (Rs.)</th>
<th>Animal Sale Amount (Rs.)</th>
<th>Other Sale Amount (Rs.)</th>
</tr>
</thead>
<tbody>
#foreach ($months as $item )
<tr>
<td>{{ $item->$months }}</td>
</tr>
#endforeach
</tbody>
</table>
Thanks in Advance
During your #foreach() loop, $item is not an Object, it is a String 'Mar-2022' through 'Apr-2021'. You need to adjust your code:
#foreach($months as $key => $label)
<tr>
<td>{{ $label }}</td>
<tr>
#endforeach
If you need the 1 through 12 values, they are available in each iteration as $key.

How to calculate using data from get() in controller

I have some data from a table and I'm doing an eloquent get for it. So far from what I know is when using get(), I need to loop it first using foreach to get the data.
My question is how to move my logic code to controller? so I just need to pass it to view. Because I'm doing it on blade directly
Bellow is my controller, I'm just simply get a data from database:
$attendances = Attendance::where('company_id', Auth::user()->company_id)->get();
#foreach ($attendances as $attendance)
// How to move this php code to my controller?
#php
$work_hour_start = $attendance->work_hour_start;
$attendance_time = \Carbon\Carbon::parse($attendance->attendance_time)->format('H:i:s');
$tolerance = \Carbon\Carbon::parse($attendance_time)->addMinutes($attendance->late_tolerance);
if ($tolerance > $work_hour_start) {
$is_late = 'Late';
} else {
$is_late = 'On Time';
}
#endphp
<tr>
<td>{{ $attendance->employee->name }}</td>
<td>{{ Carbon\Carbon::parse($attendance->attendance_time)->format('H:i:s') }}</td>
<td>{{ $attendance->location_library->location_name }}</td>
<td>{{ $is_late }}</td>
</tr>
#endforeach
I want my blade to be clean, but I don't know how to do that.
You could add attendance_time to the $casts property and make tolerance/is_late accessors in the Attendance Model
# Attendance.php
class Attendance extends Model
{
...
protected $casts = [
'attendance_time' => 'datetime',
];
...
public function getToleranceAttribute()
{
return $this->attendance_time->addMinutes($this->late_tolerance);
}
public function getIsLateAttribute()
{
return $this->tolerance > $this->work_hour_start
? 'Late'
: 'On time';
}
...
}
#foreach ($attendances as $attendance)
<tr>
<td>{{ $attendance->employee->name }}</td>
<td>{{ $attendance->attendance_time->format('H:i:s') }}</td>
<td>{{ $attendance->location_library->location_name }}</td>
<td>{{ $attendance->is_late }}</td>
</tr>
#endforeach
Just do it, move the logic to your controller and set it up in your $attendances collection. Something like this:
$attendances = Attendance::where('company_id', Auth::user()->company_id)->get();
foreach ($attendances as $key => $attendance){
$attendances[$key]->attendance_time = \Carbon\Carbon::parse($attendance->attendance_time)->format('H:i:s');
if (\Carbon\Carbon::parse($attendances[$key]->attendance_time)->addMinutes($attendance->late_tolerance > $attendance->work_hour_start) {
$attendances[$key]->setAttribute('is_late', 'Late');
} else {
$attendances[$key]->setAttribute('is_late', 'On Time');
}
}
return view('your-view', ['attendances' => $attendances]);
Now it will be able to iterate on your template:
#foreach ($attendances as $attendance)
<tr>
<td>{{ $attendance->employee->name }}</td>
<td>{{ $attendance->attendance_time }}</td>
<td>{{ $attendance->location_library->location_name }}</td>
<td>{{ $attendance->is_late }}</td>
</tr>
#endforeach

Get sum of minutes of specific project

I want to get total minutes. Example: joylinkhk 240 + 180 = 420. How can I get a total minute of a specific user?
controller
public function search(Request $request) {
$date = explode(' - ', $request->date);
$auth = Auth::user();
$hourLog = Hourlog::with('project', 'user');
if ($auth->user_type == 1) {
$hourLog->where("user_id", $auth->id);
}
$data = [
"date" => $date,
// 'projects' => Project::whereIn('id', $request->project)->get(),
'projects' => Project::with('users')->whereIn('id', $request->project)->get(),
'users' => User::with(['hourlog' => function ($query) use ($request) {
$query->whereIn('project_id', $request->project);
}])->whereIn('id', $request->user)->get(),
];
return view('cms.projectreport.projectreport-list', $data);
}
HTML view
#foreach($users as $user)
<tr>
<td>{{$user->name}}
</td>
#foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}
</td>
#endforeach
</tr>
#endforeach
Laravel collections are very powerful and offer such functionality out of the box.
Below is a example of how you can take a collection of arrays and sum by its property hour_work. The collect function is a quick way to create a collection like the $user->hourlog already is.
collect([
['hour_work' => 198],
['hour_work' => 93],
['hour_work' => 51],
['hour_work' => 112],
])->sum('hour_work');
// Result: 454
As #danny-van-der-sluijs said, you can use sum on a collection
#foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
#foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}</td>
#endforeach
</tr>
#endforeach
<tr>
<td>Grand Total</td>
<td>{{ $users->sum(fn($user) => $user->hourlog->sum('hour_work')) }}</td>
</tr>
Note:
$users->sum(fn($user) => $user->hourlog->sum('hour_work'))
Is an arrow function that came with php 7.4, If you are using a version below 7.4 you have to do it like this
$users->sum(function($user) {
return $user->hourlog->sum('hour_work');
});
You can sum in foreach loop, but get the result outside of foreach loop. You need to define first the variable outside of foreach $sum_total = 0;, then you can sum inside foreach like this :
<?php $sum_total = 0; ?> // define here
#foreach($users as $user)
<tr>
<td>{{$user->name}}
</td>
#foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}
</td>
<?php
$sum_total += (intval)$hourlogs->hour_work
?>
#endforeach
</tr>
<tr>
<td>{{ $sum_total }}</td>
</tr>
#endforeach

Resources