Chris Chris - 8 days ago 5
PHP Question

Laravel Creating default object from empty value when creating an Eloquent object

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.

Answer

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; }