In this episode, we take a look at how to make the employee
parameter on our checkout route completely optional. We'll start by tweaking our web routes, adding a question mark to the parameter to indicate it's optional. You'll see that with Laravel's route model binding, if an employee isn't passed, we just get an empty employee object, which isn't particularly helpful.
The next step is to change how we send the employee to our front end. We want it to be null
if there wasn't an employee, instead of an empty object. That's where the Eloquent exists
property comes in handy—we check if the employee exists and only pass it down if it does, otherwise we send null
.
Once that's sorted, we update our checkout view so it doesn't try to access properties on a nullable object, adding checks (and a simple placeholder for the profile photo) whenever the employee isn't present. This way, the page doesn't error out when no employee is selected, and everything looks tidy.
Finally, we explain how later on, when the user makes selections, we'll put the employee back into the URL, and everything will just work as before, but now with full support for cases where there's no employee initially. So, after this episode, your checkout flow is much more flexible!