1

I'm having this error: Creating default object from empty value in the line with the code:

if ( !$clients->isEmpty() ){ $giftcard->clients_id = $clients[0]->id; }

The whole function:

public function handle($request, Closure $next)
{
    if ( empty($request->session()->get('fixedGiftcard')) )
    {
        $sales = $this->sales->with(['giftcards'])->all();

        if ( $sales->isNotEmpty() ){
            $found=[];
            foreach ($sales as $sale) {
                if ( !empty($sale->giftcard_id) ){
                    $giftcard = $this->giftcards->findBy('id', $sale->giftcard_id);
                    if ( empty($giftcard->sales_id) ){
                        $clients = $this->clients->findWhere(['ic' => $sale->ic]);
                        if ( !$clients->isEmpty() ){ $giftcard->clients_id = $clients[0]->id; }
                        $giftcard->sales_id = $sale->id;
                        $giftcard->save();
                        $found[]=$sale->id;

                    }else if ( $giftcard->sales_id != $sale->id ){
                        $sale->giftcard_id = NULL;
                        $sale->save();
                        $found[]=$sale->id;
                    }
                }
            }
        }

        $giftcards = $this->giftcards->findWhere([['sales_id','!=', null]]);

        if ( $giftcards->isNotEmpty() ){
            $found=[];
            foreach ($giftcards as $giftcard) {
                $sale = $this->sales->findBy('id', $giftcard->sales_id);
  // continues

The error message: Laravel error message

Jorge Epuñan
  • 710
  • 7
  • 9
  • Possible duplicate of [Creating default object from empty value in PHP?](https://stackoverflow.com/questions/8900701/creating-default-object-from-empty-value-in-php) – Bram Verstraten Jul 29 '19 at 18:02

1 Answers1

0

This means that $giftcard is not an object and probably even NULL, but by assigning a property to it, it's converted into an object.

In the following lines you create the $giftcard variable and check if the id property is set, but it's possible no result is found and $giftcard is NULL.

$giftcard = $this->giftcards->findBy('id', $sale->giftcard_id);
if ( empty($giftcard->sales_id) ){

This is not an error but a warning, and because of the error reporting level, this message is shown.

You should fix this by checking if $giftcard is valid:

if (!is_null($giftcard)) {
    // Your code
}
Bram Verstraten
  • 1,414
  • 11
  • 24