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.

0

1 Answer 1

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; }
Sign up to request clarification or add additional context in comments.

2 Comments

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().
Welcome and +1 because you deleted it but undone the action again :-)

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.