5

I'm trying to save an object to the database for a game I'm building on a website, but I keep getting this error:

Creating default object from empty value

Here's the code I'm using:

    foreach( $input['items'] as $key=>$itemText ){
        $item = ($input['itemIDs'][$key] === 'NA') ? new GameItem() : GameItem::find($input['itemIDs'][$key]);
        // if updating this item, check that it is assigned to this game
        if( !is_null($item->game_id) && $item->game_id != $game->id ){ continue; }
        $item->game_id = $game->id;
        $item->item = $itemText;
        $item->answer = $input['answers'][$key];
        $item->save();
    }

The error occurs at the if statement. I tried commenting it out, and then the error occurred at the $item->game_id = $game->id; line.

I've var_dumped both $item and $game, and both are valid Eloquent objects. I even var_dumped the result of the if statement with no problems, so I'm at a loss as to what's happening.

I just noticed if I do

var_dump($item->toArray()); die();

right before the $item->save(); line, it doesn't throw any errors and shows me the array just fine.

What could be the problem then? I suppose it has to do with saving the item, but I don't understand it at all.

Chris
  • 4,277
  • 7
  • 40
  • 55

1 Answers1

5

The following line:

$item = ($input['itemIDs'][$key] === 'NA') ? new GameItem() : GameItem::find($input['itemIDs'][$key]);

Always doesn't return a GameItem object so when you try to use a property on NULL value then this error appears. So you should always check if the $item is not NULL using something like this:

if( !is_null($item) && $item->game_id != $game->id ) { continue; }

Instead of this (At first make sure $item is not NULL before you use $item->game_id):

if( !is_null($item->game_id) && $item->game_id != $game->id ){ continue; }
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 3
    Thanks. I just figured out my problem, and this wasn't actually it, but it's true that the way I was doing it could have resulted in an error in other circumstances. I actually swapped out !is_null with empty(). – Chris Jun 14 '14 at 21:46
  • Welcome and +1 because you deleted it but undone the action again :-) – The Alpha Jun 14 '14 at 21:49