How can I pass a variable to every view in Laravel without having to pass it from every controller?

Leif_Lundberg :

I am trying to make a notification badge show the amount of unread messages a user has. The following works:

// Controller
public function messages() 
{
    $messages = MessagesController::getMessages();
    $newNotificationNumber = MessagesController::getNumberOfNewMessages();

    return view('pages.messages', compact('messages'), compact('newNotificationNumber'));
}

My app.blade.php file is structured like so:

// html stuff
@include('layouts.navbar')
<main class="py-4 bg-white">
  <div class="container">
    @yield('content')
  </div>
</main>

The navbar shows the number like so:

<span class="badge badge-pill badge-primary">{{ $newNotificationNumber ?? '' }}</span>

If I include compact('newNotificationNumber') in every single controller function my notifications work like I want, but that is tedious and prone to error. Any suggestions?

zlatan :

You could do create a new controller, let's say AppController, which will extend Laravel's default App\Http\Controllers controller. Inside this new controller, create your constructor with all the data you need, and share them to all the views:

public function __construct(Request $request)
{
    $messages = MessagesController::getMessages();
    $newNotificationNumber = MessagesController::getNumberOfNewMessages();
    View::share('languages', $languages);
    View::share('newNotificationNumber', $newNotificationNumber);
}

After that, you can extend AppController in every other controller where you need your variables:

class YourController extends AppController

All that is left to do now is to extend AppController constructor in YourController:

public function __construct()
{
    parent::__construct();
}

This way, you will have access to $languages and $newNotificationNumber variables in all the views you're using in your YourController.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345944&siteId=1