schellingerht
schellingerht

Reputation: 5796

Laravel 5.1 : Passing Data to View Composer

I'm using view composers in Laravel 5.1: nice. But how can I pass parameters to a view composer?

In my case I send week info (previous, current, next week, including the dates) to my view with de view composer. The current week is variable, not only from an url, but also from the controller.

public function compose(View $view)
{
   // I need a parameter here (integers)
}

Upvotes: 6

Views: 8794

Answers (3)

Ankush Gazta
Ankush Gazta

Reputation: 11

I think if you want to pass some data to the view composer from controller then you can use sessions. Set the data from the controller in the session and you can get data from session in the view composer. This did the trick for me without doing any complex stuff

Controller

    public function index()
    {
       session(['key' => 'value']);
       return view('your_view');
    }

View Composer

    public function compose(View $view)
    {
        $data = session('key');
        return $view->with('your_data',$data);
    }

Upvotes: 0

Elisha Senoo
Elisha Senoo

Reputation: 3594

All the data you pass to your view in the controller will be available in the view controller. Use the getData method on the view instance like this:

$view->getData()["current_week"];

In your particular case, you can do this:

public function compose(View $view)
{
   $current_week = $view->getData()["current_week"];
   //use $current_week as desired 
}

You can also get the data in the route (route parameters) from the request like this:

request()->route()->getParameter('week_number');

Upvotes: 10

Moppo
Moppo

Reputation: 19275

If you have to pass parameters from a controller to a view composer, you can create a wrapper class for the composer and pass data to it whenever needed. Then, when you're done setting up you data, you can compose the view:

ComposerWrapper class

public function __construct(array $data)
{
    $this->data = $data;
}

public function compose()
{        
    $data = $this->data;

    View::composer('partial_name', function( $view ) use ($data) 
    {
        //here you can use your $data to compose the view
    } );
}

Controller

public function index()
{
    //get the data you need
    $data = ['first_value' = 1]; 

    //pass the data to your wapper class
    $composerWrapper = new ComposerWrapper( $data );

    //this will compose the view
    $composerWrapper->compose();

   //other code...
}

Upvotes: 9

Related Questions