I have three models
Member
public function getFullNameAttribute()
{
return $this->lastname . ", " . $this->firstname;
}
public function memberships()
{
return $this->hasMany('App\Membership');
}
Membership
public function member()
{
return $this->belongsTo('App\Member');
}
public function club()
{
return $this->belongsTo('App\Club');
}
Club
public function memberships()
{
return $this->hasMany('App\Membership');
}
I am trying to return a json response of all the members who belong to a given club whose memberships meet certain conditions;
public function members($id)
{
$members = Member::whereHas('memberships', function ($query) use ($id) {
$query->where('club_id', '=', $id)
->where('date_expiry', '>=', Carbon::now())
->where('member_type_id', '=', 1);
})->get()->sortBy('full_name')->pluck('id', 'full_name' );
return Response::json($members );
}
Route for this is
Route::get('clubs/members/{club}',['as'=>'clubs.members','uses' =>'ClubController@members']);
Note that 'full_name' is an accessor, not a database field.
I've noted that there is nothing I can see in inspecting the $members array after the query that names the elements, nor is there anything in the json response.
If I dd($members) I get
Collection {#255 ▼
#items: array:79 [▼
144 => "Doe, John"
221 => "Doe, Jane"
]
}
and in json I might expect to see
{"members":[{"id":"144","full_name":"Doe, John"},
{"id":"221","full_name":"Doe, Jane"}]}
but I actually get
{"144":"Doe, John",
"221": "Doe, Jane"}
If I do a simple
$members = Member::all();
then I get output which appears as "fully formed" json like
[
{
"id": 144,
"join_date": "2009-01-01",
"username": "john.doe",
"email": "[email protected]",
"firstname": "John",
"lastname": "Doe",
"initials": "",
"address": "123 Anywhere St",
"city": "Somewhere",
"province": "ON",
"postal_code": "A1B 2C3",
"country": "CA",
"created_at": "2016-11-11 11:44:03",
"updated_at": "2016-11-11 18:38:28"
},
How can I get correct json output returned from my controller with this query?
Thanks in advance!