Ogunlana Michael
Ogunlana Michael

Reputation: 33

How to Pass multidimensional array to API using laravel

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

FRUITS

Animal

Country

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

Upvotes: 2

Views: 866

Answers (1)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

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
        ];
    }

Upvotes: 1

Related Questions