Home > Back-end >  Laravel how to get value from different tables at the controller
Laravel how to get value from different tables at the controller

Time:07-18

I have a jQuery call in my page that takes data from a link I made in the controller like this:

public function api(Request $request , $project_id){

    return Program::where('project_id',$project_id)->get();
}

result :

[{"id":178,"project_id":37,"level_id":57,"zone_id":45,"ps":"2021-09-03","as":null,"pc":"2021-09-14","ac":null,"created_at":"2021-07-30T08:42:38.000000Z","updated_at":"2021-07-30T08:42:38.000000Z"},{"id":179,"project_id":37,"level_id":57,"zone_id":46,"ps":"2021-09-11","as":null,"pc":"2021-09-19","ac":null,"created_at":"2021-07-30T08:46:43.000000Z","updated_at":"2021-07-30T08:46:43.000000Z"},{"id":180,"project_id":37,"level_id":57,"zone_id":47,"ps":"2021-09-16","as":null,"pc":"2021-09-24","ac":null,"created_at":"2021-07-30T08:47:09.000000Z","updated_at":"2021-07-30T08:47:09.000000Z"},{"id":181,"project_id":37,"level_id":58,"zone_id":45,"ps":"2021-09-15","as":null,"pc":"2021-09-28","ac":null,"created_at":"2021-07-30T08:48:54.000000Z","updated_at":"2021-07-30T08:48:54.000000Z"},{"id":182,"project_id":37,"level_id":58,"zone_id":46,"ps":"2021-09-20","as":null,"pc":"2021-10-03","ac":null,"created_at":"2021-07-30T08:49:15.000000Z","updated_at":"2021-07-30T08:49:15.000000Z"},{"id":183,"project_id":37,"level_id":58,"zone_id":47,"ps":"2021-09-25","as":null,"pc":"2021-10-08","ac":null,"created_at":"2021-07-30T08:49:39.000000Z","updated_at":"2021-07-30T08:49:39.000000Z"}]

Now im trying to change the value of zone_id to come from a different table I have that that has id = xx, name=xx. I usually do this by using where() but there is no page here so what would be the way to do this at the controller?

enter image description here

CodePudding user response:

you can use WITH if ORM is setup in model, or you can use joins to get zone table along with program. it would look something like this.

return Program::where('project_id',$project_id)
    ->join('zones', 'programs.zone_id', '=', 'zones.id')
    ->get();

CodePudding user response:

Here is another answer that I found using Models:

$result = Program::where('project_id',$project_id)->get();
    foreach($result as &$row){
        $row->zone_name = Zones::where('id',$row->zone_id)->first()->name ?? '-';
    }
return $result;
  • Related