-3

I have a discount block on my site. In the table with items there is a column discount and if it has a value > 0, then the block with discounts is displayed. If there are no discounts, the discount block should not be displayed. And there is a problem with this. If there are no discounts, I get an error Undefined offset: 0.

My code:

$date = Carbon::today();
$count_discount = count(Item::where('discount', ">=", 1)->where('updated_at', '>=', $date)->get());
$item_bd = Item::where('discount', ">=", 1)->where('updated_at', '>=', $date)->orderByRaw('RAND()')->take(5)->get();
$classid = $item_bd[0]->classid;
$name = $item_bd[0]->market_hash_name;
$old_price = $item_bd[0]->price;
$discount = $item_bd[0]->discount;
$new_price = $item_bd[0]->price - (number_format($item_bd[0]->price / 100 * $discount, 2));

And in the blade i use:

@if ($count_discount === 0)
// no discount
@else
// block with dicsount
@endif

If there is a discount in the database, the discount block is displayed perfectly, if there are no discounts, I get an error.

How can I fix this error?

OMR
  • 11,736
  • 5
  • 20
  • 35
aston_ua
  • 39
  • 6
  • 1
    Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – El_Vanja Mar 21 '20 at 16:47
  • no, it's not my answer – aston_ua Mar 21 '20 at 16:56
  • you can't access to index `0` if there is not an index `0`. Add a conditional before `$item_bd[0]....` – porloscerros Ψ Mar 21 '20 at 17:02

1 Answers1

0

You can use empty() in your blade. In your controller use this code

$count_discount = Item::where('discount', ">=", 1)->where('updated_at', '>=', $date)->get();

Then in your blade use:

@if(empty($count_discount))
Do something if no discount
@else
Do something with if discount is exist
@endif
OMR
  • 11,736
  • 5
  • 20
  • 35
praadit
  • 41
  • 1
  • 7
  • Unfortunately this did not help :( if there are no discounts in the database, I continue to receive this error – aston_ua Mar 22 '20 at 12:23