Views

View Composers

Metoda me View::share

app/Providers/AppServiceProvider.php

namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        View::share(['key' => 'value']);
    }

    public function register()
    {
        //
    }
}

Metoda me rutë

routes/web.php

View::composer('*','App\Http\ViewComposers\MyViewComposer');

app/Http/ViewComposers/MyViewComposers.php

<?php

namespace App\Http\ViewComposers;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\View\View;

class MyViewComposer
{
    protected $users;
    protected $current_user;

    public function __construct(User $users)
    {
        $this->users = $users;
    }

    public function compose(View $view)
    {
        $view->with(['users' => $this->users->count(), 'current_user' => Auth::user()]);
    }
}

resources/views/welcome.blade.php

<div class="title m-b-md">
    Total  users { { $users } }<br>
    @if ($current_user)
    Current user { { $current_user->name } }
    @endif
</div>

Metoda me Service Provider

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        View::composer('*','App\Http\ViewComposers\MyViewComposer');
    }

    public function register()
    {
        //
    }
}

app/Http/ViewComposers/MyViewComposer.php

<?php

namespace App\Http\ViewComposers;
use App\User;
use Illuminate\View\View;

class MyViewComposer
{
    protected $users;

    public function __construct(User $users)
    {
        $this->users = $users;
    }

    public function compose(View $view)
    {
        $view->with(['users_count' =>  $users->count]);
    }
}

Metoda me Service Provider të vecantë

config/app.php

'providers' => [

        App\Providers\ViewComposerServiceProvider::class,

    ],

app/Providers/ViewComposerServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider
{

    public function boot()
    {
        view()->composer(
            '*',
            'App\Http\ViewComposers\MyViewComposer'
        );
    }

    public function register()
    {
        //
    }
}

app/Http/ViewComposers/MyViewComposer.php

<?php

namespace App\Http\ViewComposers;
use App\User;
use Illuminate\View\View;

class MyViewComposer
{
    protected $users;

    public function __construct(User $users)
    {
        $this->users = $users;
    }

    public function compose(View $view)
    {
        $view->with(['users_count' =>  $users->count]);
    }
}