Skip to content
Advertisement

Laravel return json with eloquent collection relationship values

I have the following function inside the UsersApiController class :- public function getKhatmas()

{
    $user = Auth::user();
    $khatmas = $user->khatmas;
    return response()->json($khatmas);
}

The above code give the following response :-

[
    {
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": 2,
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    },
    {
        "id": 4,
        "hash": "5ec72b7005126",
        "type": 2,
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    },
]

Relationship function in User Model file :-

public function khatmas()
    {
        return $this->hasMany('AppKhatma');
    }

AppKhatma file content :-

public function type()
    {
        return $this->belongsTo('AppKhatmaType');
    }

In above json response , (“type”: 2) is the foreign key of AppKhatmaType Model . I want instead of json response with the foreign key of KhatmaType Model, i want it to return the column “title” from AppKhatmaType to be like this :-

{
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": "this is title from AppKhatmaType Model",
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    }

`I tried with the following :-

$khatmas = $user->khatmas->with('type');

But it return error : Method IlluminateDatabaseEloquentCollection::with does not exist

Advertisement

Answer

Fixed by using the following query builder:-

public function getKhatmas()
{
    $user = Auth::user();

    $khatmas = Auth::user()->khatmas()
    ->select('hash','type_text','status','expiry_date','type_id')
    ->with('type')->get();

    return response()->json($khatmas);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement