0

I want use $unreadMessages in my layout but I don't know which controller is used globally for layouts. It is in dashboardController, but I get this error:

Undefined variable: unreadMessages (View: /myhost/resources/views/layouts/app.blade.php) (View: / myhost/resources/views/layouts/app.blade.php)

In which controller can I define this variable so I can use it globally?

This code is for $unreadMessages in the dashboardController:

<?php

class DashboardController extends Controller
{

    public function index()
    {
        \Artisan::call('status:check');
        $unreadMessages = TicketMessage::where(['is_read' => 0])->whereIn('ticket_id', $ticketIds)->whereNotIn('user_id', [Auth::user()->id])->count();


        return view('dashboard', compact(
            'unreadMessages'
        ));
    }
}
DarkMukke
  • 2,469
  • 1
  • 23
  • 31
Amirhossein
  • 217
  • 1
  • 5
  • 16
  • That should work just fine. No special controller/model/whatever needed to use variables in a layout page. Are there any unread messages? (`dd($unreadMessages);`) – brombeer Dec 27 '18 at 13:16
  • tnx but where are I put _@include('app', array('unreadMessages' => $unreadMessages))_ – Amirhossein Dec 27 '18 at 13:29
  • Possible duplicate of [Laravel: Where to store global arrays data and constants?](https://stackoverflow.com/questions/26854030/laravel-where-to-store-global-arrays-data-and-constants) – DarkMukke Dec 27 '18 at 13:33
  • 1
    Possible duplicate of [Laravel 5 - global Blade view variable available in all templates](https://stackoverflow.com/questions/29715813/laravel-5-global-blade-view-variable-available-in-all-templates) – Codemaker2015 Dec 27 '18 at 13:44

3 Answers3

1

you can resolve this issue by using the following code in Route.php file:

view()->share('unreadMessages', $unreadMessages);
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
0

In your dashboard.blade.php, there is likely a reference to @include('layouts/app') or something similar. If not, do a search of your code for a reference similar to that.

You'll need to pass $unreadMessages to that sub-view. You are passing it into the main blade (dashboard.blade.php), but not the included blade within dashboard (app.blade.php).

So, you will need something like:

@include('layouts/app', array('unreadMessages' => $unreadMessages))

Here are a few articles that might assist further:

cfnerd
  • 3,658
  • 12
  • 32
  • 44
0

You can do that with a ServiceProvider, in the boot function, for example :

 public function boot() {
    ...

    view()->composer(['layouts.app'],function($view) {
        $unreadMessages = TicketMessage::where(['is_read' => 0])->whereIn('ticket_id', $ticketIds)->whereNotIn('user_id', [Auth::user()->id])->count();
        $view->with('unreadMessages',$unreadMessages)
    });
 }
lovis91
  • 1,988
  • 2
  • 14
  • 24