0
votes

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('App\Khatma');
    }

App\Khatma file content :-

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

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

{
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": "this is title from App\KhatmaType 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 Illuminate\Database\Eloquent\Collection::with does not exist

1
can you try this Auth::user()->load('khatmas.type')Aslam
@Aslam I tried, i am getting "type": null,Q8root
You could use join in the query, but I think you have the relation defined backwards, or the foreign key 'type' in the wrong table, because if KhatmaType belongsTo Khatma, the foreign key should be in KhatmaType and not in Khatma.porloscerros Ψ

1 Answers

0
votes

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);
}