Return employee count based on relationship - php

I have a employees table and a attendances table
In employees Model
public function Attendance(){
return $this->hasMany(Attendance::class, 'employees_id', 'id');
}
Attendances table i have these column
id, employees_id, in_time, out_time, attendance_status_id, remarks
I want return those employee who has al least one attendance for a specific month which i will input in month field and it will filter based on in_time column

You can use the has() function when getting the Employee details. The has will only return those records if the Employee has any relational data in the Attendance table. You can also refer this link.
$employees = Employee::has('Attendance')->get();
Now you can simply use the count() function the display the total Attendance of the Employee. For the count please refer this link.
#foreach ($employees as $employee)
Total attendance: {{ $employee->Attendance->count() }}
#endforeach

Related

Foreach according to collection attribute

I have a existing laravel project on php 7.4.
It has users table, patient_appointmnets table.
In users table it contains both patient and doctor with role_id
And there is a doctor_details table which contain only basic info.
The patient_appointments table has
user_id, doctor_id, date, start_time and end_time
The problem is if do
PatientAppointment:whereDate('date', Carbon:now()->format('Y-m-d')->get() ;
And use foreach in blade
I get appointments wise column.
So e.g if a doctor has multiple appointments on that day. I got same doctor column multiple times.
But i want all appointments go in single column for particular dooctir id.
There is no direct doctor tablebwhich contains appointment. On patient_appointmnets table has doctor_id and user_id
So i want collection according to doctor where it contains all appintment
I could do join like:
$var = DoctorDetail:join('users.id', '=', 'doctor_derail.user_id')->select('doctor_detail.*')->get();
then,
for(i=0; i <= count($var) ; i++)
{
$var[$i->appointments] = PatientAppointment::whereDate('date', Carbon::now()->format('Y-m-d')->get();
}
return $var;
but not work. But in dd it show appointments inside doctor_detail collection. But if i do foreach in blade, it shows builder:get() expects 1 for very first get() query..
Any other solution to do same thing.
I believe the key to solve your problem is to use the groupBy method after retrieving all the appointments.
I assume you got the following relationships in the User and PatientAppointment table.
class User extends Model
{
public function doctorDetail()
{
return $this->hasOne(DoctorDetail::class);
}
}
class PatientAppointment extends Model
{
public function doctor()
{
$this->belongsTo(User::class, 'doctor_id');
}
public function patients()
{
$this->belongsTo(User::class, 'patient_id');
}
}
In the controller, you can retrieve all the appointments on that day and group by the doctor_id field, so you got all the appointments belonging to the same doctor:
public function index()
{
$appointmentsGroupedByDoctors = PatientAppointment:whereDate('date', Carbon:now()->format('Y-m-d'))
->get()
->groupBy('doctor_id');
return view(..., compact('appointmentsGroupedByDoctors'));
}
In the view, you can do something like:
#foreach($appointmentsGroupedByDoctors as $doctorId => $appointments)
<p>Doctor Name: {{$appointments->first()->doctor?->doctorDetail->name}}</p>
#foreach($appointments as $appointment)
// Listing the appointments belonging to the same doctor here.
#endforeach
#endforeach

Laravel Eloquent thee tables relationship query

I have three mysql tables :
students (constrained with USER_ID)
student_in_tournament (constrained with STUDENT_ID and TOURNAMENT_ID)
tournaments
I need an eloquent query who take ALL students by specified USER_ID and if these students are in the student_in_tournament table, it needs to join with the tournament table.
If these students are not in the student_in_tournament, they don't need to join something.
At the end, I need ALL students from one specific USER_ID, with the tournament joined if he exists in the student_in_tournament table...
I tried a inner join, but it don't give me ALL the students, only these who are in the student_in_tournament table. I also tried Student::with('studentInTournament.tournaments') but it gives me 'null' in the tournaments
Thanks
Try creating a M:N relation between your Student and Tournament models. Since your table and column names do not conform to what Eloquent expects, you'll need to pass all 4 parameters when creating the relationship.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure
// Student model
public function tournaments()
{
return $this->belongsToMany(Tournament::class, 'student_in_tournament', 'STUDENT_ID', 'TOURNAMENT_ID');
}
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-defining-the-inverse-of-the-relationship
// Tournament model
public function students()
{
return $this->belongsToMany(Student::class, 'student_in_tournament', 'TOURNAMENT_ID', 'STUDENT_ID');
}
$students = Student::query()
->where('USER_ID', $user_id) // or whereIn('USER_ID', $user_ids) if you have multiple user ids
->with('tournaments')
->get();
https://laravel.com/docs/8.x/blade#loops
#foreach($students as $student)
<!-- show student information -->
#forelse($student->tournaments as $tournament)
<!-- show tournament information -->
#empty
<!-- student has no tournaments -->
#endforelse
<hr>
#endforeach

How to exclude certains columns while using eloquent | Laravel

i have an group table. My main table. So i have group_hotels table this table is a pivot table. (id, group_id, hotel_id)
Now in my blade group edit page, i want to list before added pivot table like this code:
My Group model:
public function hotels(){
return $this ->belongsToMany('App\Models\Hotel','group_hotels');
}
My controller:
$group = Group::find($id);
$hotels=Hotel::all();
My blade hotel select2 field:
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}">{{$hotel->name}}</option>
#foreach ($group->hotels as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
#endforeach
The output like this: http://prntscr.com/10v13ed
Now what i want to do, in my group_hotels pivot table, if hotel id exist in group_hotels except the in the pivot table id nothing come hotel table.
In short: If the hotel_id part in the group_hotels table is present in my hotel table, I do not want to call it in the hotel variable.
One option you have is to exclude the Hotel's you don't want in your list at the query level:
Hotel::whereNotKey($group->hotels->modelKeys())->get();

Laravel - Displaying fields with many to many relationship according field in pivot table

I have this database structure
table users table office_user table offices
----------- ----------------- -------------
id * id * id *
full_name user_id name
office_id
joined_at
So in my project every office has many users and user can be joined to many offices in date (joined_at)
User.php model
public function offices()
{
return $this->belongsToMany('App\Office)->withPivot('joined_at');
}
Office.php model
public function users()
{
return $this->belongsToMany('App\User)->withPivot('joined_at');
}
OfficeController.php
public function show(Office $office)
{
$users = User::with(array('phones', 'offices' , function($query)
{
$query->orderBy('joined_at', 'desc');
}))->get();
return view('dashboard.offices.show', compact(['office', 'users']));
}
I need two things :
1- Get current users list for every office
2- Count of current users in every office
I already achieve this:
<h3>{{ $office->name }}</h3><span>{{ $office->users->count() }}</span>
#foreach ($office->users as $user)
<li>{{ $user->full_name }}</li>
#endforeach
But the result is not as expected it gives me all users in certain office and count of them regardless there joined date
I want the list of last joined users to this office and count of them according joined_at field in pivot table
Thank you and Sorry for my english
But the result is not as expected it gives me all users in certain office and count of them regardless there joined date
When you do $office->users->count() that is the expected behavior because you are retrieve all the associated users of every office at any time, so given that you returned all this users, the count() executed in the collection will count all of them.
Your pivot attribute is just a timestamp, so how would you reduce the number of users returned? users that joined the office today/in the last hour/in the last 15 min maybe?
If so, you can add constrains to your count() method to get the results you want.
As an example, in the following lines we are gonna constraint the associated offices that has a joined_at that belongs to today:
public function show(Office $office)
{
$users = User::with([
'phones',
'offices' => function ($offices) {
$offices->whereDate('joined_at', '>', now()->startOfDay());
},
])->get();
return view('dashboard.offices.show', compact([office, 'users']));
}
Check this section of the documentation:
Constraining Eager Loads
Sometimes you may wish to eager load a relationship, but also specify
additional query conditions for the eager loading query. Here's an
example:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
In this example, Eloquent will only eager load posts where the post's
title column contains the word first. You may call other query
builder methods to further customize the eager loading operation:
$users = App\User::with(['posts' => function ($query) {
$query->orderBy('created_at', 'desc');
}])->get();

Eloquent order by one-to-one-related column

Good morning everyone!
I'm using Laravel 5.0 and Eloquent to build a displaying page for results of some replies on the database.
Replies are in reservations table, which "belongs" to users table since every reservation is linked to a person.
class Reservation extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
}
I would like to display results, the reservations, ordered by the last name column of the user. So like:
$reservations = Reservation::orderBy( /*users.last_name*/ )->get();
But I dont'know how. Thank you in advance for your time.
You'll need to join the tables to order by a foreign column.
$reservations = Reservation::join('users', 'users.id', '=', 'users.reservation_id')
->orderBy('users.last_name', 'asc')->get();

Categories