I got a question about PHP compact.
In the Laravel controller, I am returning the next values with compact:
return view('vote.cast', compact('canvote', 'opinionClosed', 'userVoteDecision'));
I have a problem here however. The variable 'userVoteDecision' is sometimes optional, and will not always be set by the controller.
Is there a way, to let compact ignore a variable, if it does not exist? (by making the return of the value 'userVoteDecision' optional?)
Or is there a better workaround, to fix this?
Thank you in advance.
Regards Dave
CodePudding user response:
If you want workaround, so take this solution:
if(isset($userVoteDecision)) {
return view('vote.cast', compact('canvote', 'opinionClosed', 'userVoteDecision'));
} else {
return view('vote.cast', compact('canvote', 'opinionClosed'));
}
In general, it is better to set $userVoteDecision = null;
And assign a value to a variable only if there is one.
In all other cases, let the variable exist as null