PHP code example of artis-auxilium / laravel-lazy-view-models

1. Go to this page and download the library: Download artis-auxilium/laravel-lazy-view-models library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

artis-auxilium / laravel-lazy-view-models example snippets


use ArtisAuxilium\LaravelLazyViewModels\ViewModel;

final class InvoiceViewModel extends ViewModel
{
    public function __construct(
        public readonly Invoice $invoice,
    ) {}

    public function total(): string
    {
        return number_format($this->invoice->total, 2) . ' €';
    }

    public function customerName(): string
    {
        return $this->invoice->customer->name;
    }
}

return view('invoices.show', new InvoiceViewModel($invoice));

final class ButtonViewModel extends ViewModel
{
    public function label(): callable
    {
        return fn () => strtoupper($this->text);
    }
}

final class InvoiceViewModel extends ViewModel
{
    public function formattedTotal(string $currency): string
    {
        return number_format($this->invoice->total, 2) . " {$currency}";
    }
}

final class ListViewModel extends ViewModel
{
    /** @return object[] */
    public function items(): array
    {
        return [(object) ['value' => 'a'], (object) ['value' => 'b']];
    }
}

final class ExampleViewModel extends ViewModel
{
    public function base(): string
    {
        return 'result'; // expensive computation, e.g. a DB query
    }

    public function dependent(): string
    {
        return $this->base . '_dep'; // property access, not base()
    }
}

use ArtisAuxilium\LaravelLazyViewModels\Attribute\Ignore;

final class InvoiceViewModel extends ViewModel
{
    public function total(): string
    {
        return $this->formatAmount($this->invoice->total);
    }

    #[Ignore]
    public function formatAmount(float $amount): string
    {
        return number_format($amount, 2) . ' €';
    }
}

use ArtisAuxilium\LaravelLazyViewModels\Attribute\IsHtml;

final class ArticleViewModel extends ViewModel
{
    #[IsHtml]
    public function renderedBody(): string
    {
        return Str::markdown($this->article->body);
    }
}
blade
<h1>{{ $customerName }}</h1>
<p>Total: {{ $total }}</p>
blade
@php
    /** @see InvoiceViewModel */
    /** @var string $customerName */
    /** @var ViewValue<string> $total */
@endphp