Kieran Headley
Kieran Headley

Reputation: 993

Run a command in Laravel on every page load

I want to load a command with Laravel on each page load;

$mail_count = mail::where('to_id', '=', Auth::user()->id)->where('read', '=', '0')->count('read');

What would be the best way to do this? This then needs to output the result in the master template for the page.

Upvotes: 2

Views: 6062

Answers (2)

The Alpha
The Alpha

Reputation: 146191

Use a view composer for master template, for example:

// app/providers/ComposerServiceProvider.php
public function boot()
{
    view()->composer(
        'layouts.master', 'App\Http\ViewComposers\MasterComposer'
    );
}

Then create the Composer class:

namespace App\Http\ViewComposers;

use Auth;
use App\Mail;
use Illuminate\View\View;

class MasterComposer
{
    public function compose(View $view)
    {
        $mail_count = Mail::where('to_id', Auth::user()->id)
                          ->where('read', 0)
                          ->count('read');
        $view->with('mail_count', $mail_count);
    }
}

Finally, you can use {{ $mail_count }} in your master view to print out the result. So, in this case, what it's doing is, whenever your views\layouts\master.blade.php will be rendered the compose method will be called and $mail_count will be attached into the view. Make sure to use the exact name for the view, I've used layouts.master (views/layouts/master.blade.php) for this example.

Upvotes: 7

Nechemya Kanelsky
Nechemya Kanelsky

Reputation: 673

You can use it in a laravel provider go to the AppServiceProvider.php inside the boot function paste variable

$mail_count = mail::where('to_id', '=', Auth::user()->id)->where('read', '=', '0')->count('read');

then you can do it with one of the options:

1.

view()->composer('*', function($view) use($mail_count){
    $view->with('mail_count', $mail_count);
});

2.

view()->share('mail_count', $mail_count);

Upvotes: 3

Related Questions