How to create view composer in Laravel?

Updated 19 May 2023

Today we are going to learn how to use view composer in Laravel, before using this first of all we need to know the Agenda why we need this, and where we need to use it.

Sometimes we required a common piece of data throughout the entire website and we want to manage that piece of information from a single place in that case we can use view composer in Laravel.

There are two types of view composers that Laravel provides.

1. Class-based view composer

– Class-based view composer can use when we have some data and we want to separate or isolate logic with a separate class to share it from a single place.

Here, you can find a class-based view composer.

In this class, we are counting the number of registered users and sharing across the website from a single place.

2. Closure-based view composer –

Second approach we can create a view composer directly without creating a class.

You can simply create a new service provider and add the below code, Currently, I am assuming you have AppServiceProvider.php which is located in App/Providers directory.

You just need to add the below code inside the boot method of your AppServiceProvider.php class. After adding the below code userCount and productCount values will be available on home page.

You can access it inside the home page, the same as you were passing to view from the controller as a compact function.

We can also share the user count and product count with multiple views, above example, we have passed only on the home page.

The below example is for passing data from a view composer, which is a closure-based view composer for specific views.

Now our class-based and closure-based view composer is ready now we can place it into our respective service provider.

In our example, we are assuming we have the default AppServiceProvider.php which is located in App/Providers directory.

Conclusion – 

In this article, we have learnt how to create  Class-based and Closure-based view composer in Laravel and how we are passing common data for specific views and entire views of Laravel application.

Thank you for reading this tutorial. We hope you found it helpful. If you have any questions or encounter any issues, please feel free to leave a comment below.

Feel free to hire laravel developers to build your custom solutions on laravel. For exploring the available extensions for Bagisto, you can check out bagisto.com.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home