Home > Net >  How can I format the array on a specific format in my laravel controller function?
How can I format the array on a specific format in my laravel controller function?

Time:04-01

I'm currently creating a laravel vue spa, and just wondering on how can I get designation names with these designation id's with the same structure. This is the json of designation id's:

[
  [
    1,
    5
  ],
  [
    1,
    3
  ]
]

This is my getDesignations function in EmployeesController.php:

    public function getDesignations($id) {
        $employee_designation_ids = Employees::find($id)->pluck('designation_id')->toArray();
        $designation_name = [];
        foreach ($employee_designation_ids as $employee_designation_id) {
            $designation = Designations::where('id', '=', $employee_designation_id); 
            //$designation_name[] =  $designation;
        }

        return $employee_designation_ids;
    }

CodePudding user response:

If you want specifically that format, you can do it like this (with a lot of guesses in my part since you did not share your Tables structures)

public function getDesignations($id) {
    $employee_designation_ids = Employees::find($id)->designation_id;
    return [[$id, $employee_designation_ids]];
}

But why are you returning a double table for a single row result.

CodePudding user response:

Thanks for all your help! I've managed to fix it with this method in my controller:

public function getDesignations(Request $request, $id) {
        $employee_designation_ids = Employees::where('id', $id)->pluck('designation_id');
        return Designations::whereIn('id', $employee_designation_ids[0])->pluck('name');
    }

  • Related