pjmil
pjmil

Reputation: 2097

Laravel - Return associated models to json

I have two models, Threads and Leads.

I'm trying to return the lead with the threads as a JSON object but all I am getting is a leads field that is null.

Threads Model;

public function leads()
{
    return $this->belongsTo('Leads');
}    

Leads Model;

public function threads()
{
    return $this->hasMany('Threads');
}

ThreadsController;

public function getLead($id=null)
{
    $thread = Threads::thread($id)->with('leads')->get();

    return Response::json($thread)->setCallback(Input::get('callback'));
}

Upvotes: 3

Views: 432

Answers (1)

totymedli
totymedli

Reputation: 31058

Instead of with(), try to load() them:

$thread = Threads::thread($id)->load('leads')->get();

Also, a note on your namings: your Threads model's leads() function should be called lead() because a Thread got only one Lead (thats why you used belongsTo()), but this is only for readibility.

Upvotes: 2

Related Questions