Ad

How Can I Pass A Variable To Every View In Laravel Without Having To Pass It From Every Controller?

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad