Search code examples
phplaraveldatabasegetparent-child

Laravel How to get all Child data belongs parent orderby desc?


So i want to get all child data from parent data order by id descending/recent store like this

{
list parent data recent : {
 "List data": {
        "id": 2,
        "title": "Test",
        "number": "10231232",
        "created_at": null,
        "updated_at": null
    },
    "All child by parent id": [
        {
            "id": 5,
            "title": "lalala",
            "parent_id": 2,
            "created_at": null,
            "updated_at": null
        },
    }
}

in my controller i was create code model::where() function and i dont know about the format where is, i used this code to find parent data and child belongs id parent, and i want using this code for get recent parent data with child. thanks

 public function recent(){
        try{
            $parent = $this->parent->orderBy('id', 'desc')->limit(1)->get();
            $child= Child::where('parent_id', '=', $parent)->get();
            return response()->json(['List parent recent' => $parent , 'all child data' => $child], 300);
        }catch (ModelNotFoundException){
            return response()->json(['Error' => '404', 'Message' => 'Item not found or not created yet!'], 404 );
        }

    }

i was try this code and store data at postman but the problem is that the child data doesnt exist

 {
    "List updates recent": [
        {
            "id": 2,
            "title": "uasda",
            "version": "6969",
            "created_at": null,
            "updated_at": null
        }
    ],
    "All features by id": []
}

Solution

  • You made a mistake, In this line

    Child::where('parent_id', '=', $parent)
    

    you are comparing id to a object, which will return null,

    try this

     public function recent(){
            try{
                $parent = $this->parent->orderBy('id', 'desc')->firstOrFail();
                $child= Child::where('parent_id', $parent->id)->get();
                return response()->json(['List parent recent' => $parent , 'all child data' => $child], 300);
            }catch (ModelNotFoundException){
                return response()->json(['Error' => '404', 'Message' => 'Item not found or not created yet!'], 404 );
            }
    
        }