kisonay
kisonay

Reputation: 361

Retrieving data and relationships for JSON output

I'm new to all of this and trying to wrap my head around Laravel. I have two models setup and one pivot table. I'm trying to output some JSON in the following format:

[
    {
        "question": "somequestiongoeshere",
        "tags": [
            "tag1",
            "tag2"
        ]
    },
    {
        "question": "somequestiongoeshere",
        "tags": [
            "tag1",
            "tag2"
        ]
    }
]

I've only been able to output either tags or questions but not in the format above. Any guidance would greatly be appreciated.

Question.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model {

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

}

Tag.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model {

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

}

Controller

public function index() {
    return Question::all();
}

Upvotes: 0

Views: 179

Answers (1)

Steve Adams
Steve Adams

Reputation: 2837

Eloquent, by default, doesn't load relations until they're called (lazy loading). You need to specify relations to load, or 'eager load' them (opposite of lazy loading). For example:

$questions = Question::with('tags')->get();

See more here.

Upvotes: 1

Related Questions