Storing instances in Laravel Service Container that may be null

314 Views Asked by At

I'm attempting to store an instance of the current department in Laravels Service Container, however sometimes this department may be null.

The department itself is loaded from session and retrieved as such:

private function resolveCurrentDepartmentFromSession(Request $request)
{
    $departmentId = $request->session()->pull(self::CURRENT_DEPARTMENT);

    return Department::find($departmentId);
}

I store it in the Service Container by:

App::instance('Department\Current', $department);

And retrieve it as:

$department = App::bound('Department\Current') ? App::make('Department\Current') : null;

Are there no way to resolve the instance IF set, and return null otherwise? Something like App::instanceIfSet('Department\Current')? Or should I avoid storing "sometimes null" values in the Service Container? I could make a class CurrentDepartment which stores it as a property and store this in the container as a Singleton instead, but would like to know if I'm missing something essential about the Service Container first.

1

There are 1 best solutions below

0
On

You could use the optional helper:

return optional(Department::find($departmentId));

Now when you call the bound class any property you attempt to access against it when it is null will also return null.