Home > Software design >  Why is Laravel's flash message not outputting 0?
Why is Laravel's flash message not outputting 0?

Time:10-10

I have a function that counts the amount of free space for uploading files.

If the user tries to upload, for example, 5 files, and there is only space for one, then a flash message will appear with the amount of free space - 1.

But if there is no space, I expect to see 0, but the flash message is not displayed at all

dd returns the correct number and I pass that value to flash

$count = $this->checkCountAdditionalPhotosInProduct($product, $request->additional_photos, $this->imgPath($userId), $uploadService);
//dd($count);
return redirect()->back()->with('count', $count);

And view

@if (session('count'))
    <div  role="alert" >
        Your free space - {{ session('freeSpace') }}
        <button type="button"  data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
@endif

The product stores a serialized array of photo links. I check if there is a string in the product field, I deserialize it, count the number of elements. Dalle subtract the received amount from the constant which is equal to 5 and return the result

public function checkCountAdditionalPhotosInProduct (Product $product): int
{
    $currentProductPhotos = $product->additional_photos ? count((array)unserialize($product->additional_photos)) : 0;
    $freePlace = self::TOTAL_PRODUCT_PHOTOS - $currentProductPhotos;
    return $freePlace;
}

CodePudding user response:

That's expected and normal. When count is 0 and you want to retrieve it from the session, using session('count'), it returns 0 as you need but the issue resides in the if statement: @if (session('count')), which will result in @if 0 which evaluates to FALSE thus the code portion inside that if statement WILL NEVER get executed when session('count') returns 0.

The fix is fairly simple, just change this:

@if (session('count'))

Into this:

@if (session('count') !== null)

That's because the session() function returns NULL (by default) when the wanted key (in your case the key is count) cannot be found in the session.

Please be advised that the default value returned by the session() function when the key cannot be found in the session can be customized by specifying what you want to return in that case by passing the wanted default value as the second parameter. Learn more here.

  • Related