Laravel 5.1 : Passing Data to View Composer

前端 未结 3 572
天命终不由人
天命终不由人 2021-02-06 15:20

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, inc

3条回答
  •  囚心锁ツ
    2021-02-06 16:03

    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...
    }
    

提交回复
热议问题