2

I am fetching data from two tables using join, however, I want my result to return a multi-dimensional array , i.e.

FRUITS

  • Apple
  • Mango
  • Orange

Animal

  • Dog
  • Cat
  • Cow

Country

  • Germany
  • UK
  • USA

So, that is what I want it to return, see my code below

 Route::get('all-category', function(){

$category = DB::table('directory_companies')
             ->join('categories','directory_companies.categories_id', '=', 'categories.id')
            ->select('categories.name', 'directory_companies.*') 
             ->get();
return response()->json($category);

How do I return it to display like the list above in multidimensional array, I am using Laravel to build the API

1

1 Answer 1

1

You can use eloquent resource for displaying any structure you want for api.

Create resource and Reourse Collection

php artisan make:resource directory_companies
php artisan make:resource directory_companies_collection --collection
$category = DB::table('directory_companies')
             ->join('categories','directory_companies.categories_id', '=', 'categories.id')
            ->select('categories.name', 'directory_companies.*') 
             ->get();

return response()
    ->json(new directory_companies_collection(new directory_companies($category)));

And in your directory_companies resource:

public function toArray($request)
    {
        return [
            // Any structure of data you want to present
        ];
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.