Home > Software engineering >  Foreach according to collection attribute
Foreach according to collection attribute

Time:11-27

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.

CodePudding user response:

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
  • Related