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

ctyler's avatar

Are View Composers only for Static Queries?

I am rather new to View Composers so I am a little confused.

I am working on a training site. I have a view for classes that shows the number of students allowed, students enrolled and the number of sets remaining. I think that a View composer would be great for this but the problem is, in my limited understanding of composers, I cannot seem to figure out how to pass a variable to the view composer. Is this possible.

So for instance if the url is /coursecat/1/course/1 Can I pass the Course ID into the View Composer?

Thank you!

0 likes
3 replies
Jaytee's avatar

View composers are used when the same data needs to be shared across multiple view files. Technically speaking, it can be dynamic or static data, however as far as I am aware, you cannot pass parameters to change the results, as these are setup in ServiceProviders.

For example (using this from a Laracasts video lesson): Imagine you have a navbar, and you want to show the title of the latest blog post.

The problem: In order for the navbar to receive the latest blog post, you would need to pass that blog post to every view that is rendered that includes the navbar, which in 99% of cases, would be every view. So for every method in your controller, you would do something like this:

// stuff that relates to this method

$latestPost = Post::latest()->first();

return view('my.view', compact('latestPost'));

Solution: Use a view composer to pass the $latestPost variable to the view that contains the navbar (e.g: app.blade.php or navbar.blade.php) so that the navbar has access to it

DarkRoast's avatar
Level 8

I would use view composers for partial views which are reused in many different places but all require some data from somewhere e.g. a menu view which requires always requires data from a database to build itself.

You can use the router from inside a view composer to access information about the current route:

https://laravel.com/docs/5.8/routing#accessing-the-current-route

https://laravel.com/api/5.8/Illuminate/Routing/Router.html

1 like
ctyler's avatar

@DARKROAST - Brilliant! That's exactly what I needed.

 $params = Route::current()->originalParameters();
        // Dependencies automatically resolved by service container...
        //$this->users = $users;
        $studentsEnrolled = Enrollment::totalStudentsEnrolled($params['course']);
        $this->studentsEnrolled = $studentsEnrolled;

One thing for anyone looking this up after the fact. If you create a Service Provider for your view composers, be sure to execute: php artisan config:clear and php artisan clear-compiled Laravel did not recognize my service provider until after. Hopefully that will save someone some time!

Thank you.

Please or to participate in this conversation.