Return related eloquent models altogether in json format

Viewed 34

I'm learning Eloquent Model Relationships in Laravel. In my demo project I have two tables Sets and Cards, they have One to many relationship. One Set has many Cards and a Card belongs to a Set.

I want the output to hold both Sets and Cards together in nested JSON array, Cards under Sets. I have set the relationships in both models.

My expected result


[
  {
    "set_id":1,
    "name":"English",
    "description":"English Language",
    "created_at":"2020-03-31T15:41:55.000000Z",
    "updated_at":"2020-03-31T15:41:55.000000Z"},
    "cards: 
       {
          "card_id":1,
          "name":"Greetings",
          "description":"Greetings related questions",
          "set_id":1,
          "created_at":"2020-03-31T15:45:03.000000Z",
          "updated_at":"2020-03-31T15:45:03.000000Z"
       }
  }
]

Set.php

<?php

namespace App;
use App\Card;

use Illuminate\Database\Eloquent\Model;

class Set extends Model
{
    protected $table = "sets";

    public function cards() {
        return $this->hasMany('App\Card');
    }
}


Card.php

<?php

namespace App;

use App\Set;
use Illuminate\Database\Eloquent\Model;

class Card extends Model
{
    protected $table = "cards";

    public function sets() {
        return $this->belongsTo('App\Set');
    }
}


In my Controller I have tried to get my result by this line return Set::all()->cards;, but it says Property [cards] does not exist on this collection instance. My migration files have foreign key set in Cards table, so I think the relationship between tables is made correctly or maybe I'm wrong.

I have read the detailed Laravel Doc for Eloquent Relationships, but did not find any query that returns related models together in a nested JSON, the way I'm expecting.

0 Answers
Related