Jithesh Kt
Jithesh Kt

Reputation: 2043

Global variable which may or may not change on each view Laravel 5.2

My requirement is simple. Since I am new to Laravel I don't know how exactly achieve it.

I have count of something say, I have count of pending friend requests. I have sidebar.blade.php in my view folder. This side bar is being called in all my other blade files like @include('sidebar').

Now, I want to display pending friend request count in my sidebar file, which will be practically displaying all over my website. How to achieve this ?

Upvotes: 1

Views: 37

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163968

You need to create view composer. Create service provider which will register composer:

public function boot()
{
    // Using class based composers...
    View::composer(
        'sidebar', 'App\Http\ViewComposers\SidebarComposer'
    );

And then composer class, something like this:

public function __construct(Requests $requests)
{
    // Dependencies automatically resolved by service container...
    $this->requests = $requests;
}

public function compose(View $view)
{
    $view->with('friendRequests', $this->requests->count());
}

Upvotes: 3

Related Questions