How can I share an object instance between two controllers?

Posted 7 months ago by Digitalized

Hi all,

Please can someone suggest a good way to share the same object between two controllers? I'm scratching my head trying to come up with a good solution

Here is my issue:

I have an application where users can undertake question-based assessments.

The assessment comprises questions specific to the assessment, and the questions are randomly generated. The process is two parts - firstly the user is presented with some questions, secondly, they submit their answers and those same questions must be marked.

I have attempted to save my assessment object instance into the service container (as a singleton) in the first controller, then access it via the second controller - however it cannot be resolved out of the service container

I assume this is because of where I am registering the singleton and its scope

My reason for going down the singleton route - when I create an assessment I want the questions to be "locked in" for the duration of the assessment, so I thought it a singleton might be a good pattern in this case


// Controller 1  

// A new assessment is instantiated via AssessmentFactory::lessonAssessment

// When the questions() method is called the first time, some random questions are chosen from a wider pool of questions. The method uses lazy loading, so each subsequent time the questions method is called, the exact same questions are returned.

public function show(Course $course, Unit $unit, Lesson $lesson):View 
{
    $lessonAssessment = AssessmentFactory::lessonAssessment($unit, $lesson);

    // I have tried the following as a test!
    app()->singleton('lesson_assessment', function() use ($lessonAssessment) {
        return $lessonAssessment; 
    });

    $questions = $lessonAssessment->questions();
        
    return view('lesson_show', compact('course', 'unit', 'lesson', 'questions'));
}


// Controller 2

// This controller should retrieve the same lessonAssessment instance created in the first controller and then mark the user answers which were stored in the session as the user answered each question.


public function assess(Unit $unit, Lesson $lesson):RedirectResponse
    {

        // The line below throws a ReflectionException ("Class lesson_assessment does not exist") - so Laravel is unable to resolve it out of the service container!

        $lessonAssessment = resolve('lesson_assessment');
        
        // some other logic here which performs the assessment
    
    }

Any advice would be appreciated!

Please sign in or create an account to participate in this conversation.