I am trying to get the practice area record of lawyers from practice_areas table along side each time I get a lawyer’s record from lawyer_profiles_table. This two tables (practice_areas and lawyer_profiles) are related with a pivot table named (lawyer_practice_area)
This code below are from the LawyerProfile Model
public function practice_areas() { return $this->belongsToMany(PracticeArea::class, "lawyer_practice_area", "practice_area_id", "lawyer_id"); }
I tried getting it through an attribute by doing the below
public function getPracticeAreasAttribute() { return $this->practice_areas(); }
and then appended it this way
protected $appends = ["practice_areas"];
but I keep getting this result on postman – “withtimestamps”:”false”
See output below:-
"id": 1, "city": "Hintztown", "state": "Iowa", "longitude": "-163.884102", "latitude": "-18.127927", "lawyer_profile": { "id": 26, "email": "serena.barrows@yahoo.com", "name": "Raoul Hegmann", "primary_location_id": 1, "photo_id": 39, "phone_number": "887.299.6204 x456", "about_lawyer": "Distinctio eos omnis autem error.", "practice_areas": { "withTimestamps": false } } },
Advertisement
Answer
Probably what you want to use is Eager loading.
Take a look at the documentation.
$books = AppBook::with('author')->get(); foreach ($books as $book) { echo $book->author->name; }