nSathees
nSathees

Reputation: 11

Laravel session has value

if(! session()->exists('disease', $val)){
    $request->session()->push('disease', $val);
}

I want to add a value (text) for disease only if it is not in array. How to archive this in Laravel 8? I can assign the session array to a var and do a php array_unique. But is there a beautiful way in Laravel?

Thank you all.

Upvotes: 0

Views: 364

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29278

->exists() only takes a single argument, $key:

https://github.com/laravel/framework/blob/8.x/src/Illuminate/Contracts/Session/Session.php#L64.

If you want to check that 'disease' is in the session and equals $val, then you can do:

if (session()->get('disease', null) !== $val) {
  session()->push('disease', $val);
}

If 'disease' in the session is present and already equal to $val, then nothing will happen. Otherwise, it will add it to the session.

Edit: Since 'disease' is an array, not a single value, you'll need to adjust your code a bit:

$diseases = session()->get('disease', []);
if (!in_array($val, $diseases)) {
  $diseases[] = $val;
  session()->put('disease', $diseases);
}

You should be able to use ->push() as suggested in the comments, and as evidenced by your current 'disease' array, but the same idea applies; only append to the array if it's not already there.

Upvotes: 1

Related Questions