$company = Company::with(['job' => function($query){
$query->orderBy('created_at');
}])->get();
https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
Please or to participate in this conversation.