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

Sidart's avatar
Level 12

orderBy created at on a relationship table

Hello, so i have 2 tables in one to many relationship.

I have a Company table and a Job table.

A Company can post many jobs.

Now i want to fetch all the jobs that all the companies have made with both the company data and job data and also order them by created_at.

I am using this in my controller:

    $company = Company::with('job')->get();
    return view('Jobs.jobs')->withCompany($company);

And this is how i show the results in the blade file:

   @foreach ($company as $comp)
        @foreach ($comp->job as $jobs)
            <div class="col-xs-12 col-sm-6 col-md-4">
              <a href="{{route('availiableJob',$jobs->id)}}">
                <div class="thumbnail">
                    <img  src="{{asset('images/companylogos/'.$comp->logo)}}" alt="...">
                    <div class="caption">
                      <h3 class="text-center" style="text-transform:uppercase;font-size:16px;font-weight:600;">{{$jobs->name}}</h3>
                      <p class="pull-right" style="text-transform:uppercase;font-size:13px;font-weight:600;">{{$jobs->city}}</p>
          <p style="text-transform:uppercase;font-size:13px;font-weight:600;">{{$jobs->type}</p> 
                     </div>
                 </div>
                </a>
               </div>
        @endforeach
   @endforeach 

If i go ahead and orderBy with this query i am getting created_at value from the company table, which is obvious.

Now is there a way to orderBy the job created_at field?

0 likes
2 replies
Sidart's avatar
Level 12

@st8113 Very clean an nice solution but the problem is that now i do get jobs by created at but it gives me first all the jobs from one company, then the next company etc, so it kinda sorts the results by company and then by job and created at!

Any ideas?

Please or to participate in this conversation.