How can I let compact ignore non-existing variables?

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.



Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x