skip to Main Content

At my database i has column items, and in this coluln i has value:

[{"id":588,"user_id":1,"item_id":801,"created_at":"2020-12-16T11:55:40.000000Z","updated_at":"2020-12-16T11:55:40.000000Z","item":{"id":801,"market_hash_name":"Blackshield Protodrone Armor","image":"-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KW1Zwwo4NUX4oFJZEHLbXK9QlSPcUmoBVWSV6fSuGu387sW1JmKwFDiamtJBJs1_baPjBH79S3q4iEhfnxJ4TCnmRE5MF0mNbN9J7yjRrnrkNqNjr7IICSIFVsaVzYr1O4kOq915O16pyfm3Bi6SVzt3nYnUC0n1gSOXdKDzqL","exterior":"Mythical","rarity":"Mythical","color":"D2D2D2","is_stattrak":0,"price":1.3,"created_at":null,"updated_at":"2020-12-16T19:45:02.000000Z"}}]

I need to take value of item_id, i try to make it like:

<td>{{ $bet->items[item_id] }}</td>

But i received error: Use of undefined constant item_id – assumed ‘item_id’ (this will throw an Error in a future version of PHP)

If try:

<td>{{ $bet->items['item_id'] }}</td>

I received: Illegal string offset ‘item_id’

Or if try:

<td>{{ $bet->items["item_id"] }}</td>

I received same error: Illegal string offset ‘item_id’

My full code at conttoller:

    $bets = Bet::query()->where('user_id', $user->id)->orderBy('id', 'asc')->get();
    foreach ($bets as $bet) {
        $profit += round($bet->win - $bet->bank, 2);
    }

At views:

@foreach($bets as $bet)
    <tr>
        <td>#{{ $bet->id }}</td>
        <td>#{{ $bet->game_id }}</td>
        <td>{{ round($bet->bank, 2) }} $</td>
        <td>{{ round($bet->win, 2) }} $</td>
        <td>{{ round($bet->multiplier, 2) }}x</td>
        <td>{{ round($bet->auto_withdraw, 2) }}x</td>
        <td>{{ $bet->items["item_id"] }}</td>
        <td>{{ $bet->created_at }}</td>
    </tr>
@endforeach

How i can fix it?

2

Answers


  1. you have two option.
    first :
    turn your json into array and access it like this:

    $items_array = json_decode($bet->items,true);
    $item_id = $items_array[0]['item_id'];
    

    second or you can do it like object:

    $items_object = json_decode($bet->items);
    $item_id = $items_array[0]->item_id;
    
    
    Login or Signup to reply.
  2. if your column "item" is a string, you need to change it to json by using json_decode().

    1.Array

    $item_array = json_decode($item, true);  //if(second parameter is true), it will turn to array
    $item_id = $items_array[0]['item_id'];  //then your item_id is
    

    2.Object

    $item_object = json_decode($item);  //if(second parameter is false), it will turn to object
    $item_id = $items_array[0]->item_id;  //then your item_id is
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search