Data providers encapsulate logic for Inertia views, keep your controllers clean and simple.

Overview

Laravel Data Providers for Inertia.js

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Data providers encapsulate logic for Inertia views, keep your controllers clean and simple.

Installation

We assume you've already got Inertia installed, so you can just install this package via composer:

composer require webfox/laravel-inertia-dataproviders

Usage

Using a Data Provider

Data providers take advantage of the fact that Inertia::render can accept Arrayables as well as standard arrays and so are used
instead a standard array in the Inertia::render method. They can also be used as discrete attributes in the data array.

use App\Models\Demo;
use App\DataProviders\DemoDataProvider;

class DemoController extends Controller
{
    public function show(Demo $demo)
    {
        return Inertia::render('DemoPage', new DemoDataProvider($demo));
    }
    
    public function edit(Demo $demo)
    {
        return Inertia::render('DemoPage', [
          'some' => 'data',
          'more' => 'data',
          'demo' => new DemoDataProvider($demo),
        ]);
    }
}

What Does a Data Provider Look Like?

Data providers can live anywhere, but we'll use App/Http/DataProviders for this example.

The simplest data provider is just a class that extends DataProvider, any public methods or properties will be available to the page as data.
A fully featured data provider might look like this:

<?php
declare(strict_types=1);

namespace App\Http\DataProviders;

use Inertia\LazyProp;
use App\Services\InjectedDependency;
use Webfox\InertiaDataProviders\DataProvider;

class DemoDataProvider extends DataProvider
{

    public function __construct(
        /*
         * All public properties are automatically available in the page
         * This would be available to the page as `demo`
         */
        public Demo $demo;
    )
    {
        /*
         * Data providers have a `staticData` property, which you can use to add any data that doesn't warrant a full
         * property or separate method
         */
        $this->staticData = [
            /*
             * This will be available to the page as `title`
             */
            'title' => $this->calculateTitle($demo),
        ];
    }
    
    /*
     * All public methods are automatically evaluated as data and provided to the page.
     * ALWAYS included on first visit, OPTIONALLY included on partial reloads, ALWAYS evaluated
     * This would be available to the page as `someData`.
     * Additionally these methods are resolved through Laravel's service container, so any parameters will be automatically resolved.
     */
    public function someData(InjectedDependency $example): array
    {
        return [
            'some' => $example->doThingWith('some'),
            'more' => 'data',
        ];
    }
    
    /*
     * If a method returns a `Closure` it will be evaluated as a lazy property.
     * ALWAYS included on first visit, OPTIONALLY included on partial reloads, ONLY evaluated when needed
     * Additionally the callback methods are resolved through Laravel's service container, so any parameters will be automatically resolved.
     * @see https://inertiajs.com/partial-reloads#lazy-data-evaluation
     */
    public function quickLazyExample(): Closure
    {
        return function(InjectedDependency $example): string {
            return $example->formatName($this->demo->user->name);
        };
    }
    
    /*
     * If a method is typed to return a LazyProp, it will only be evaluated when requested following inertia's rules for lazy data evaluation
     * NEVER included on first visit, OPTIONALLY included on partial reloads, ONLY evaluated when needed
     * Additionally the lazy callback methods are resolved through Laravel's service container, so any parameters will be automatically resolved.
     * @see https://inertiajs.com/partial-reloads#lazy-data-evaluation
     */
    public function lazyExample(): LazyProp
    {
        return Inertia::lazy(
            fn (InjectedDependency $example) => $example->aHeavyCalculation($this->demo)
        );
    }
    
    /*
     * `protected` and `private` methods are not available to the page
     */
    protected function calculateTitle(Demo $demo): string
    {
        return $demo->name . ' Demo';
    }

}

Using Multiple Data Providers

Sometimes you might find yourself wanting to return multiple DataProviders DataProvider::collection is the method for you. Each DataProvider in the collection will be evaluated and merged into the page's data, later values from DataProviders will override earlier DataProviders.

use App\Models\Demo;
use App\DataProviders\TabDataProvider;
use App\DataProviders\DemoDataProvider;

class DemoController extends Controller
{
    public function show(Demo $demo)
    {
        return Inertia::render('DemoPage', DataProvider::collection(
            new TabDataProvider(current: 'demo'),
            new DemoDataProvider($demo),
        ));
    }
}

You can also conditionally include DataProviders in the collection:

use App\Models\Demo;
use App\DataProviders\TabDataProvider;
use App\DataProviders\DemoDataProvider;
use App\DataProviders\EditDemoDataProvider;
use App\DataProviders\CreateVenueDataProvider;

class DemoController extends Controller
{
    public function show(Demo $demo)
    {
        return Inertia::render('DemoPage', DataProvider::collection(
            new TabDataProvider(current: 'demo'),
            new DemoDataProvider($demo),
        )->when($demo->has_venue, function (DataProviderCollection $collection) use($demo) {
            $collection->push(new CreateVenueDataProvider($demo));
        })
        ->unless($demo->locked, function (DataProviderCollection $collection) use($demo) {
            $collection->push(new EditDemoDataProvider($demo));
        }));
    }
}

Or you can use the DataProviderCollection::add method to add a DataProvider to the collection later:

use App\Models\Demo;
use App\DataProviders\TabDataProvider;
use App\DataProviders\DemoDataProvider;
use App\DataProviders\CreateVenueDataProvider;

class DemoController extends Controller
{
    public function show(Demo $demo)
    {
        $pageData = DataProvider::collection(
            new TabDataProvider(current: 'demo'),
            new DemoDataProvider($demo),
        );
        
        if($demo->has_venue) {
            $pageData->add(new CreateVenueDataProvider($demo));
        }

        return Inertia::render('DemoPage', $pageData);
    }
}

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

We welcome all contributors to the project.

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Clone do instagram utilizando Laravel, Vue, Inertia, Tailwind

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Laravel Starter With Laravel, Vite, Vue 2, Inertia.js, Ziggy

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Laravel Starter With Laravel, Vite, Vue 2, Inertia.js, Ziggy, Typescript

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

A Sidecar function to run Inertia server-side rendering on Lambda.

Sidecar SSR for InertiaJS 🚨 This is currently very much in beta! You can see a fully working Jetstream + Inertia + Sidecar demo repo at hammerstonede

Laravel Starter Kit (Inertia-SSR - Vue3 - Bootstrap 5)
Laravel Starter Kit (Inertia-SSR - Vue3 - Bootstrap 5)

Laravel Starter Kit (Inertia-SSR - Vue3 - Bootstrap 5) Use this starter kit to develop with Laravel 9 setup InertiaJs with Server Side Rendering (SSR)

Starter - Laravel, Vue, Inertia, Tailwind, Vite

Starter - Laravel, Vue, Inertia, Tailwind, Vite Laravel-vite preset Laravel 9 Vue 3 Inertia Tailwind Vite Including Sail (Docker). php 8.1 mysql 8.0 p

A clean integration between Laravel and Expose. ⚡️

A clean integration between Laravel and Expose. This package provides an artisan expose command to quickly share you site via Expose. It will also rep

This repository is pre-configured, clean and empty skeleton for creating a new projects using Kraken Framework.

Kraken Application Skeleton Note: This repository contains pre-configured application skeleton for fast creation of new projects with Kraken Framework

A package for building Admin-Interfaces that help maintaining the data of your applications
A package for building Admin-Interfaces that help maintaining the data of your applications

A package for building Admin-Interfaces that help maintaining the data of your applications. It provides an intuitive interface and the tools needed to manage your project's Users, Models and free Forms for Pages, Settings etc.

Comments
Releases(v1.1.0)
Owner
Webfox Developments Ltd
Webfox Open Source Packages
Webfox Developments Ltd
Create Migration, Seed, Request, Controller, Model and Views for your resource (CRUD)

Table of Contents Laravel Resourceful NOTE! Usage Install through composer Add Service Provider Run it! Example Generated Controller Generated Views I

Remo 62 Aug 15, 2021
A simple and clean boilerplate to start a new SPA project with authentication and more features from fortify

A simple and clean boilerplate to start a new SPA project with authentication and more features from fortify. Its like the little sister of Jetstream, but as SPA.

Tobias Schulz 11 Dec 30, 2022
a laravel package to create dynamically dashboard views in several templates ( in development)

Laravel Dashboarder A laravel package for generate admin dashboard dynamically based on Tabler template use livewire - alpinejs Installation Run the c

Laravel Iran Community 7 Dec 12, 2022
Laravel backend Inertia and Vue starter template

Inertia.js - Vue.js ve Laravel Starter Template Yunus Emre Altanay If you want to make a single page application using laravel infrastructure. This re

Yunus Emre Altanay 3 Oct 21, 2021
A starter kit that integrates Laravel with Vue CLI, Inertia.js, TailwindCSS and Vuetify

Laravel Viltify Laravel Viltify is a heavily opinionated Laravel starter kit. It's intent is to seamlessly integrate V ue, I nertia.js, L aravel, T ai

Matheus Dal'Pizzol 50 Jan 4, 2023
A template for web development using Laravel, Inertia and Svelte

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Atikur Rahman Chitholian 0 Dec 26, 2021
It's a dashboard theme/UI-Starter Kit with Laravel, Inertia and Vue (JetStream).

TailAdmin Inertia It's a dashboard theme/UI-Starter Kit with Laravel, Inertia and Vue (JetStream). Setup Directions npm install composer install Chang

Sinan AYDOÄžAN 121 Dec 31, 2022
Building Student Management CRUD with LARAVEL VUE and INERTIA

Building Student Management CRUD with LARAVEL VUE and INERTIA. the amazing thing about I got by combining these technologies is we ca build single page application or SPA .

Tauseed 3 Apr 4, 2022
An open source blog, made using Laravel, Inertia.js, and React.js. Also a learning repository.

Blog An open source Laravel-based blog. Still in progress, will be updated regularly as I wrote articles on my blog. Configurations Shared-hosting, an

Aghits Nidallah 8 Dec 6, 2022
Starterkits Project With Laravel + Inertia JS + Vue + Vuetify

Laravel InertiaJS Vuetify A laravel inertiajs vuetify starterkit Demo You can access demo app in : https://laravel-inertia-vuetify.herokuapp.com/ Feat

Ahmad Faiz Kamaludin 21 Dec 16, 2022