Optimizing Early Data Preparation with Laravel View Creators

I Nyoman Jyotisa
2 min read3 days ago

Laravel’s View Creators enable efficient preparation of data immediately after a view is instantiated. They operate earlier than View Composers, making them ideal for setting up essential view data or improving performance. Here’s how you can leverage View Creators in your Laravel application.

Registering a View Creator

To register a View Creator, use the View::creator method:

use Illuminate\Support\Facades\View;

// Registering a View Creator
View::creator('dashboard', DashboardCreator::class);

Practical Example: Dynamic Application Menu

Let’s dive into an example of using a View Creator to manage a dynamic application menu based on the authenticated user’s preferences and roles.

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)…

--

--

No responses yet