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?

4
  • use DB::setFetchMode(PDO::FETCH_ASSOC); before query builder Commented Sep 9, 2017 at 6:28
  • this is the error now, Class 'App\Http\Controllers\PDO' not found Commented Sep 9, 2017 at 6:32
  • Did you have player_type column in your auction table? You are trying to fetch an unknown property Commented Sep 9, 2017 at 6:53
  • add use PDO namespace in controller@YogeshKumarSingh Commented Sep 10, 2017 at 4:14

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.