Home Ask Login Register

Developers Planet

Your answer is one click away!

Kieran Headley February 2016

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.


Nechemya Kanelsky February 2016

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:


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


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

The Alpha February 2016

Use a view composer for master template, for example:

// app/providers/ComposerServiceProvider.php
public function boot()
        '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)
        $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.

Post Status

Asked in February 2016
Viewed 3,279 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life