简体   繁体   中英

Laravel Eloquent : Getting object instead of array

Trying to get a hotel in detail for hotel management API, in which for some hotels, getting

$hotel->rooms

as object and for some as array. The eloquent query in Hotel model as below.

public function detail($hotelid) { 
    return $this->with(['rooms','roomType'])->find($hotelid);
}

public function rooms() {
    return $this->hasMany(HotelRooms::class, 'hotels_id')->where('status','active');
}

HotelRoom Model

public function roomType(){
   return $this->hasOne(RoomType::class,'id','room_type_id')->where('status','active');
}

Controller

public function __construct(){
    $this->model = new Hotel();
}

public function hotelDetail(Request $request){

    $data = $this->model->detail($request->input('hotel_id'));

    foreach($data->rooms as $key=>$room){

        if(!$room->roomType){
            unset($data->rooms[$key]);
            continue;
        }

    }

    return response()->json([
         'status' => true,
         'status_message' => 'successful',
         'data' => $data,
    ]);
}

response

{
    "id":"id",
    "name":"name",
    "rooms":{
        "1":{},
        "2":{}
    }       
}
{
    "id":"id",
    "name":"name",
    "rooms":[
        {},
        {},
    ]       
}

When you use unset on array, your array indexes remain for each item. Same as for collection->filter() or for array_filter() that is actually used in collection->filter() . That is why you need to rebuild the indexes:

$data->rooms = array_values($data->rooms->toArray());

to reindex the array.

Or use the foreach , but push values to new array:

$filteredRooms = [];
   foreach($data->rooms as $key=>$room){

        if(!$room->roomType){
           continue;
        }
        $filteredRooms[] = $room;

    }

$data->rooms = $filteredRooms;

Or instead of foreach loop, use filter for collection in combination with values() :

$filteredRooms = $data->rooms->filter(function ($room, $key) {
    return (!$room->roomType)? false : true;
})->values();

After filtering array you have to re-index your array.

foreach($data->rooms as $key=>$room){

    if(!$room->roomType){
        unset($data->rooms[$key]);
        continue;
    }
}
$data->rooms = $data->rooms->values();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM