Home >Backend Development >PHP Tutorial >Early View Data Preparation with Laravel View Creators

Early View Data Preparation with Laravel View Creators

Emily Anne Brown
Emily Anne BrownOriginal
2025-03-06 02:43:09178browse

Early View Data Preparation with Laravel View Creators

Laravel view creator allows you to prepare data immediately after view instantiation, earlier than view combinator, which makes them ideal for setting up necessary view data or optimizing performance.

Let's look at a practical example of managing dynamic application menus:

First, register the view creator:

use Illuminate\Support\Facades\View;
// 注册视图创建器
View::creator('dashboard', DashboardCreator::class);

Next, define the view creator class:

<?php namespace App\View\Creators;

use App\Services\MenuService;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;

class ApplicationMenuCreator
{
    protected $menuService;

    public function __construct(MenuService $menuService)
    {
        $this->menuService = $menuService;
    }

    public function create(View $view)
    {
        $user = Auth::user();

        $view->with([
            'mainMenu' => $this->menuService->getMainMenu($user),
            'quickActions' => $this->menuService->getQuickActions($user),
            'recentItems' => $this->menuService->getRecentItems($user),
            'notifications' => $this->menuService->getPendingNotifications($user)
        ]);
    }
}

Register view creator in your AppServiceProvider:

// 在你的 AppServiceProvider
public function boot()
{
    View::creator('layouts.app', ApplicationMenuCreator::class);
}

Lastly, use data in layouts/app.blade.php:

<div class="sidebar">
    <nav>
        @foreach($mainMenu as $menuItem)
            <a class="https://www.php.cn/link/a754fc1765a45a6bc1a034140afd0669'active'] ? 'active' : '' }}" href="https://www.php.cn/link/a754fc1765a45a6bc1a034140afd0669'url'%5D%20%7D%7D">
                https://www.php.cn/link/a754fc1765a45a6bc1a034140afd0669'label'] }}
            </a>
        @endforeach
    </nav>

    @if(count($quickActions))
        <div class="quick-actions">
            @foreach($quickActions as $action)

                    {{ $action['label'] }}

            @endforeach
        </div>
    @endif
</div>

View creator provides early data preparation for your views, ensuring that critical data is available immediately after view instantiation. This helps improve application performance and code maintainability.

The above is the detailed content of Early View Data Preparation with Laravel View Creators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn