smita patil
smita patil

Reputation: 45

nested json response in laravel 5.7

I am new in laravel and i am creating json response for three table i am trying upto two table but i can not add third table in coding plz add some coding in my function. Table are

  1. category_type={category_type_id,category_name};
  2. main_category={main_category_id,category_type_id,main_category_name}
  3. sub_category={sub_category_id,category_type_id,main_category_id,sub_category_name}

I am nesting json upto second table now i want join third table.

function that i had created:

public function fetchCategory()
{
    $tableIds = DB::select( DB::raw("SELECT * FROM table_category_type"));

    $jsonResult = array();

    for($i = 0;$i < count($tableIds);$i++)
    {
        $jsonResult[$i]["category_id"] = $tableIds[$i]->category_id;
        $jsonResult[$i]["category_type"] = $tableIds[$i]->category_type;
        $id = $tableIds[$i]->category_id;
        $jsonResult[$i]["main_category"] = DB::select( DB::raw("SELECT *  FROM table_main_category WHERE category_type_id = $id"));

    }

    return Response::json(array(
                'success'     =>  '1',
                'data'    =>  $jsonResult),
                200
        );
}

Json obtained from my code that nested second table in first but i want nest third table in first table.

    {
        "success": "1",
        "data": [
            {
                "category_id": 1,
                "category_type": "Study",
                "main_category": []
            },
            {
                "category_id": 2,
                "category_type": "Sports",
                "main_category": [
                    {
                        "main_category_id": 1,
                        "category_type_id": 2,
                        "category_name": "Popular Sports"
                    },
                    {
                        "main_category_id": 2,
                        "category_type_id": 2,
                        "category_name": "Team Sports"
                    },
                    {
                        "main_category_id": 3,
                        "category_type_id": 2,
                        "category_name": "Racquet Sports"
                    },
                    {
                        "main_category_id": 4,
                        "category_type_id": 2,
                        "category_name": "Fitness"
                    },
                    {
                        "main_category_id": 5,
                        "category_type_id": 2,
                        "category_name": "Recreation"
                    }
                ]
            },
            {
                "category_id": 3,
                "category_type": "Other",
                "main_category": []
            }
        ]
    }

I am nesting main_category in category_type now i want nested sub_category in main_category plz need changes in coding. I am nesting three tables in one to many and many to many relation. As i am new in laravel i can not understand how send id in nested relation

Upvotes: 1

Views: 2401

Answers (1)

Albert Gargantua
Albert Gargantua

Reputation: 13

as you are new in Laravel, you may have no idea what Eloquent is. And if I understand your question right, we have 3 tables and we need to connect them via relations, so we can obtain each item relational object with data.

So we have 3 tables:

  1. category_types
  2. main_categories
  3. sub_categories

Note: it is accepted that the names of the tables are in the plural and the names of the model are singular. Like this category_types for table and CategoryType for model class.

Ok, so first of all you need to create migrations:

php artisan make:migration create_category_types_table

public function up()
{
    Schema::create('category_types', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name', 255)->nullable();
        $table->timestamps();
    });
}

php artisan make:migration create_main_categories_table

public function up()
{
    Schema::create('main_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('category_type_id')->index();
        $table->string('name', 255)->nullable();
        $table->timestamps();
    });
}



php artisan make:migration create_sub_categories_table

public function up()
{
   Schema::create('sub_categories', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->bigInteger('category_type_id')->index();
       $table->bigInteger('main_category_id')->index();
       $table->string('name', 255)->nullable();
       $table->timestamps();
   });
}

So in up of function of this migration we have an auto increment and name

Note you can write just name in this table and no category_name and category_type_id as You always know that this attributes belongs to partuclar table

Ok, next you we can create and configure our models. For CategoryTypes model we should create 2 relations for main_categories and for sub_categories, like this:

php artisan make:model CategoryType
php artisan make:model MainCategory
php artisan make:model SubCategory

And this is our Category type model code:

class CategoryType extends Model {
    protected $fillable = ['name'];

    protected $dates = [
        'created_at',
        'updated_at'
    ];

    public function mainCategories()
    {
        return $this->hasMany(MainCategory::class);
    }

    public function subCategories() {
       return $this->hasMany(SubCategory::class);
    }
}

As we define our CategoryType model realtions we can now retrieve data, that we need in our Controller:

public function fetchCategory()
{
    $categories = CategoryType::with(['mainCategories', 'subCategories'])->get();

    return response()->json($categories, 200);
}

And our json:

[
{
    "id": 1,
    "name": "Books",
    "created_at": "2019-05-19 13:24:51",
    "updated_at": "2019-05-19 13:24:51",
    "main_categories": [
        {
            "id": 1,
            "category_type_id": 1,
            "name": "Si-Fi",
            "created_at": "2019-05-19 13:26:07",
            "updated_at": "2019-05-19 13:26:08"
        },
        {
            "id": 2,
            "category_type_id": 1,
            "name": "Biography ",
            "created_at": "2019-05-19 13:26:33",
            "updated_at": "2019-05-19 13:26:34"
        },
        {
            "id": 3,
            "category_type_id": 1,
            "name": "Tall tale ",
            "created_at": "2019-05-19 13:26:57",
            "updated_at": "2019-05-19 13:26:58"
        },
        {
            "id": 4,
            "category_type_id": 1,
            "name": "Short story",
            "created_at": "2019-05-19 13:27:07",
            "updated_at": "2019-05-19 13:27:07"
        },
        {
            "id": 5,
            "category_type_id": 1,
            "name": "Fantasy",
            "created_at": "2019-05-19 13:27:17",
            "updated_at": "2019-05-19 13:27:18"
        }
    ],
    "sub_categories": [
        {
            "id": 1,
            "category_type_id": 1,
            "main_category_id": 1,
            "name": "Space exploration",
            "created_at": "2019-05-19 13:42:35",
            "updated_at": "2019-05-19 13:42:35"
        },
        {
            "id": 2,
            "category_type_id": 1,
            "main_category_id": 2,
            "name": "Historical biography",
            "created_at": "2019-05-19 13:42:36",
            "updated_at": "2019-05-19 13:42:36"
        },
        {
            "id": 3,
            "category_type_id": 1,
            "main_category_id": 5,
            "name": "The Lord of the Rings",
            "created_at": "2019-05-19 13:42:37",
            "updated_at": "2019-05-19 13:42:37"
        }
    ]
},
{
    "id": 2,
    "name": "Sports",
    "created_at": "2019-05-19 13:24:57",
    "updated_at": "2019-05-19 13:24:57",
    "main_categories": [
        {
            "id": 6,
            "category_type_id": 2,
            "name": "Popular Sports",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 7,
            "category_type_id": 2,
            "name": "Team Sports",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 8,
            "category_type_id": 2,
            "name": "Racquet Sports",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 9,
            "category_type_id": 2,
            "name": "Fitness",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 10,
            "category_type_id": 2,
            "name": "Recreation",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        }
    ],
    "sub_categories": [
        {
            "id": 4,
            "category_type_id": 2,
            "main_category_id": 6,
            "name": "Football",
            "created_at": "2019-05-19 13:42:37",
            "updated_at": "2019-05-19 13:42:37"
        },
        {
            "id": 5,
            "category_type_id": 2,
            "main_category_id": 6,
            "name": "Basketball",
            "created_at": "2019-05-19 13:42:37",
            "updated_at": "2019-05-19 13:42:37"
        }
    ]
},
{
    "id": 3,
    "name": "Study",
    "created_at": "2019-05-19 13:25:24",
    "updated_at": "2019-05-19 13:25:25",
    "main_categories": [
        {
            "id": 11,
            "category_type_id": 3,
            "name": "Web Development",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 12,
            "category_type_id": 3,
            "name": "Sofware Development",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 13,
            "category_type_id": 3,
            "name": "Mangement",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 14,
            "category_type_id": 3,
            "name": "Tourism",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 16,
            "category_type_id": 3,
            "name": "Geography",
            "created_at": "2019-05-19 13:33:36",
            "updated_at": "2019-05-19 13:33:37"
        }
    ],
    "sub_categories": [
        {
            "id": 6,
            "category_type_id": 3,
            "main_category_id": 11,
            "name": "PHP",
            "created_at": "2019-05-19 13:42:29",
            "updated_at": "2019-05-19 13:42:30"
        },
        {
            "id": 7,
            "category_type_id": 3,
            "main_category_id": 11,
            "name": "Ruby",
            "created_at": "2019-05-19 13:42:31",
            "updated_at": "2019-05-19 13:42:32"
        },
        {
            "id": 8,
            "category_type_id": 3,
            "main_category_id": 11,
            "name": "Java",
            "created_at": "2019-05-19 13:42:33",
            "updated_at": "2019-05-19 13:42:33"
        }
    ]
}

]

Hope this is will be helpful for you. And please read Laravel Docs for more information

Upvotes: 1

Related Questions