Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FREDERIC LD's avatar

How can I pass data from view or controller to view composer

Hi,

I have the following view composer

public function boot()
{
	view()->composer(['suggested-activities'], '\App\Http\Composers\Frontend\Activities\SuggestedActivitiesComposer@compose');
}
class SuggestedActivitiesComposer
{

    public function compose(View $view)
    {
            $view->with('activities', $this->doSomeAwesomeStuff($view->getData()['MYVARIABLE']) );
    }


	public function doSomeAwesomeStuff($somevar)
	{
		...
	}

}

How can I get MYVARIABLE variable from the controller? OR from the view? In my view I tried to add in my view

@include('suggested-activities', ['MYVARIABLE' => $content->id])

but that does not work ...

I don't mind getting the value from the controller if that's easier but it feels more logical to me to get the value from the view

0 likes
4 replies
jlrdw's avatar

Did you follow examples here https://laravel.com/docs/8.x/views#view-composers

And see the note in docs:

Remember, if you create a new service provider to contain your view composer registrations, you will need to add the service provider to the providers array in the config/app.php configuration file.

Then run:

php artisan config:clear
martinbean's avatar

@rffred Why are you trying to get the value from a controller in a view composer? This completely defeats the point of MVC.

Pass the data from the controller, to your view. Then you have the values from the controller. Instead of having a controller render a view, that has a view composer, that calls a controller… That just sounds like a bi-directional mess for the sake of passing a variable to a view.

FREDERIC LD's avatar

@jlrdw My view composer works fine and appears in all the pages I want to. However, I now need to pass a variable to it and that's where I need help.

@martinbean I don't want to use the controller to pass the variable. I want to use the main view in which my composer view sits in.

How do I get hold of the MYVARIABLE variable in the compose function?

martinbean's avatar
Level 80

I don't want to use the controller to pass the variable. I want to use the main view in which my composer view sits in.

@rffred That’s completely backwards. Why? Controllers send data to views; not views themselves.

You’re finding it difficult because you’re going against how MVC works. If something’s difficult, it usually means there’s a better way.

Please or to participate in this conversation.