Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mattnewark's avatar

Joining multiple tables

Hi,

I am trying to get a collection of information from three tables in my DB, The tables are: Sites Schedules Services

There is a link table that is called company_service that has the id's for each of the above and called: site_id schedule_id service_id

In my models for each of the above I have the below:

public function model_name()
     {
       return $this->belongsTo(model_name::class, 'company_service')->withPivot('company_id', 'service_id', 'site_id', 'schedule_id', 'date');
     }

So there are multiple services for each site and only one schedule for each service.

I would like to have access to the services and the schedule for a certain site in my view.

So far in my controller I have:

$tickets = Ticket::where('site_id', $id)
                          ->orderBy('time_created', 'desc')
                          ->limit(5)
                          ->get();
        $sites = Site::findOrFail($id);
        $sid = $sites->schedule()->pluck('id');
        $service_id = $sites->service()->pluck('id');
        $service = Service::findOrFail($service_id);
        $schedule = Schedule::findOrFail($sid);
        return view('site.show')
              ->with([
                'sites' => $sites,
                'service' => $service,
                'tickets' => $tickets,]);

and in my view:

@foreach ($service as $serv)
                    <tr>
                      <td>{{ $serv->service_sub_type_short_name }}</td>
                      <td>{{ $serv->description }}</td>
                      <td>{{ Schedule information needs to go here }}</td>
                      <td><button type="button" class="btn btn-xs btn-info" data-toggle="modal" data-target-id="{{ $serv->id }}" data-site-id="{{ $sites->id }}" data-target="#viewService">View</button></td>
                    </tr>
                  @endforeach 

I can see the services for each site with no problems but I need to be able to access the schedule so that I can enter it into the table and send the ID to the model.

Thanks in advance..

0 likes
0 replies

Please or to participate in this conversation.