0

I fetched data from table 'auction'

$players = DB::table('auction')->where('id',$id)->get();

I'm getting the data in this form

[
  {
    "id": 3,
    "name": "Yogesh Singh",
    "year": "BE",
    "branch": "CE",
    "division": "D",
    "achievements": "College Cricket Team",
    "base_price": 5000000,
    "status": 1,
    "manager": 0
  }
]

now I need to shift this data into another table 'team', and hence I did

DB::table('team')->insert(['player_id' => $id, 'player_type' => $player->player_type, 'name' => $player->name, 'price' => $player->price]);

it throws an error saying, Property [player_type] does not exist on this collection instance.

I'm pretty sure i'm not able to convert the data fetched from DB to array.

How do I do this?

jq170727
  • 13,159
  • 3
  • 46
  • 56

2 Answers2

2

Laravel query builder select method returns a variable of Collection type. each member is of type stdclass.

Collection has a toArraye member:

toArray()

Just notice this function returns back 2 dimension array.

Another way is using collection->first to get first member of collection and convert this stdclass into array using this approach:php stdClass to array

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amin.Qarabaqi
  • 661
  • 7
  • 19
0

It's because the $players is returning a collection since you used get(). Change it to first() which will return Model instance if exists. Also variable name is $player , not $players

$player = DB::table('auction')->where('id',$id)->first();

Now access data like:

DB::table('team')->insert(['player_id' => $id, 'player_type' => $player->player_type, 'name' => $player->name, 'price' => $player->price]);

OR

You can keep the get() and access data like this:

DB::table('team')->insert(['player_id' => $id, 'player_type' => $player[0]->player_type, 'name' => $player[0]->name, 'price' => $player[0]->price]);

Hope it's helpful.

Sreejith BS
  • 1,183
  • 1
  • 9
  • 18