phplaravellaravel-session

How to assign value if not increment? laravel


I want to assign a value if not exist else increment the value. Below is the one line code that I'm trying to achieve.

session()->put(['validation_count' => session('validation_count')++ ?? 1]);

But I end up this error below.

Can't use function return value in write context

Someone knows the perfect one line solution?


Solution

  • $validationCount = session('validation_count');
    session()->put(['validation_count' =>  ($validationCount ? $validationCount++ : 1]);
    

    Update for comment:

    I recommend with variable usage but if you want to one line:

    session ()->put ( ['validation_count' => ( session ( 'validation_count' ) ? session ( 'validation_count' ) + 1 : 1 )] );
    session ()->save ();