0

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
  • You might be misusing the service container, why cant you just add a helper to retrieve the department from the session? Commented Dec 18, 2019 at 15:41

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.