Search code examples
phplaravelhmvclaravel-3

How to pass variables to another controller in Laravel


I have a product controller and a header controller. When loading the product controller, I use Route::forward() to load my header controller.

return View::make('frontend.catalogue.product.view')
            ->with('head', Route::forward("GET", "frontend/page/head"));

I can then echo out the header on the page by doing:

<?php echo $head; ?>

Simple. However, I want to pass information to the header controller which will be defined in the product controller, such as the page title or meta description.

Ideally I would either be able to pass an array to the header, or have an instantiated class somewhere which both route requests have access to.

I've tried instantiating a library in my base controller constructor, however this gets re-instantiated on each Route::forward() request so any properties I set can't be read in the next forward.

The only way I can think of doing this is using session data, but that doesn't seem like it would be the best way to do it.

The header does need to be a controller and not just a view composer, as it deals with it's own models etc.

I know Laravel doesn't do HMVC, which would be the ideal solution, and I know there are bundles for HMVC, but I'm curious how you would approach this the Laravel way.

(Using Laravel 3.2 btw)


Solution

  • Managed to get this working how I want. For others interested:

    Instead of using

    return View::make('frontend.catalogue.product.view')
                 ->with('head', Route::forward("GET", "frontend/page/head"));
    

    I now do the following in the main request controller:

        $document = array(
            'meta_title' => 'My Title',
            'meta_description' => 'My Description',
        );
    
        // Output the view
        return View::make('frontend.catalogue.category.view')
                        ->with('head', Controller::call('frontend.page.head@index', array($document)));
    

    and in my frontend/page/head controller, I have the following:

    public function action_index($document = array()) {
    
           $meta_title = isset($document['meta_title']) ? $document['meta_title'] : 'Default Title';
    
           return View::make('frontend.page.head')
                    ->with('meta_title', $meta_title);
    
    }
    

    Props to the friendly guys on the Laravel IRC for helping with this