Laravel Eloquent relationships are defined as a method on your model eloquent class. Especially when you work with parent child relationship.
Here Laravel, We need to use hasmany relationship for ordering child in terms of id, name, created date, etc...
But sometimes we need to orderBy() parent from child, Which is a little bit difficult for the developer.
In this post your will easy to parent ordering when you have more than one child.
The parent will order from the child relationship. So below is one example that will help you with how to order parents from many child's.
In this example, One doctor has multiple clinics. So I want to get the nearest clinic's doctor's order from the latitude and longitude of the user to the clinic's doctor.
Using addSelect() the query I am fetching clinic's of the doctor. This is a doctor list but this list orderBy() from clinic latitude and longitude, So the user will get a doctor list from the nearest clinic's doctor.
Here below is a working example please check in your query.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Doctor; use App\Clinic; class HomeController extends Controller { public function getAscDoctorFromClinic(Request $request) { $latitude = $request->latitude; $longitude = $request->longitude; $doctor = Doctor::where('verification',1) ->where('status',1) ->select( 'id', 'name', 'college', 'category', 'experience', 'profile_image', 'verification', 'vaccinated', 'rating', 'success_patient' ) ->addSelect(['distance' => Clinic::select(DB::raw("6371 * acos(cos(radians(" . $latitude . ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" . $longitude . ")) + sin(radians(" .$latitude. ")) * sin(radians(latitude)))"))->whereColumn('doctor_id','doctors.id')->limit(1) ]) ->orderBy('distance','asc') ->get(); return view('doctor',compact('doctor')); } }
This will helper you to parent orderBy() from child base.
Thanks for reading our post...
We always thanks to you for reading our blogs.
Dharmesh Chauhan
(Swapinfoway Founder)Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us
Haresh Chauhan
(Co-Founder)We Are Also Recommending You :
- Upayments Gateway Integration PHP - Laravel
- Laravel 10 Create Controller Example
- Call to undefined function Gregwar\Captcha\imagecreatetruecolor()
- Arr::forget() | Laravel Helper Function
- How To Filter In Laravel Query Example
- [Fixed] Binary Does Not Exist Laravel
- Error : Using $this when not in object context update column laravel
- File name required when file upload laravel validation rules
- Email Send Using Queue In Laravel
- The GET method is not supported for this route. Supported methods: PATCH