user3201500 user3201500 - 7 months ago 42
PHP Question

Run a function or route in whole application in Laravel 5.2

I am trying to create an application where i have a user activity log. I dont want to write a special function in all the pages. I just want to metnion it once and run on all the pages or controller where ever i go. Which keep showing on the header.blade.php. And i want to keep using that log all time.

I have a function with like this.

public function headerLogs()
{
$latestActivities = Activity::with('user')->latest()->limit(10)->get();
return view('layouts.header')->with('logs', $latestActivities);
}


How can i do that?

Answer

Laravel has built-in functionality for that: View Composers. They are what you use if you want some data to be in every view that is loaded (of course you specify which views exactly)

So from the docs we would create a service provider for our view composer:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ActivitiesComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {    
        // Using Closure based composers...
        view()->composer('layout.header.activity', function ($view) {

        $latestActivities = Activity::with('user')->latest()->limit(10)->get();

        $view->with('logs', $latestActivities);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

And then you register your ActivitiesComposerServiceProvider service provider by simply adding it to the providers array in config/app.php.

So now you can simply @include('layout.header.activity') and the logs will show with no extra line of code in your controller or view

Comments