PHPackages                             maduser/laravel-viewmodel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. maduser/laravel-viewmodel

ActiveProject[Templating &amp; Views](/categories/templating)

maduser/laravel-viewmodel
=========================

ViewModels for Laravel

1.0.4(4y ago)04MITPHPPHP &gt;=7.1.3

Since Oct 24Pushed 2y ago1 watchersCompare

[ Source](https://github.com/judus/laravel-viewmodel)[ Packagist](https://packagist.org/packages/maduser/laravel-viewmodel)[ RSS](/packages/maduser-laravel-viewmodel/feed)WikiDiscussions master Synced today

READMEChangelog (5)Dependencies (2)Versions (7)Used By (0)

maduser/laravel-viewmodel
=========================

[](#maduserlaravel-viewmodel)

A long time ago, in a galaxy far away... Laravel did not have view components. This is how old this solution is. Still a valid approach, although no longer the Laravel way.

The **maduser/laravel-viewmodel** package provides an elegant way to encapsulate data and logic needed for views in Laravel applications, promoting clean separation of concerns and reusable code. By using ViewModels, you can simplify your controllers and views, making your codebase more maintainable and understandable.

Features
--------

[](#features)

- **Flexible Responses:** ViewModel can automatically determine whether to render a view or return JSON based on the request, providing flexibility for APIs and web interfaces.
- **Encapsulation of Logic:** Keep your controller clean by moving presentation logic into ViewModels.
- **Ease of Use:** Implement ViewModel with minimal setup and use it seamlessly with Laravel's response handling.

Installation
------------

[](#installation)

Install the package via composer:

```
composer require maduser/laravel-viewmodel
```

Quick Start
-----------

[](#quick-start)

### Creating a ViewModel

[](#creating-a-viewmodel)

ViewModels are simple to define. Here's an example of a ViewModel that displays a quote:

```
use Maduser\Laravel\ViewModel\ViewModel;

class MyQuoteWidget extends ViewModel
{
    protected $view = 'my-widget'; // Blade template
    protected $quote; // Quote string

    public function getQuote(): ?string
    {
        return $this->quote;
    }

    public function setQuote(?string $quote): MyQuoteWidget
    {
        $this->quote = $quote;
        return $this;
    }
}
```

### Blade Template

[](#blade-template)

Create a corresponding Blade template for your ViewModel. For the MyQuoteWidget ViewModel, the **my-widget.blade.php** file might look like this:

```

    {{ $view->getQuote() }}

```

### Using ViewModel in a Controller

[](#using-viewmodel-in-a-controller)

You can use the ViewModel in a controller to pass data to your view. Here's an example of how to use a **Page** ViewModel

```
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Maduser\Laravel\ViewModel\ViewModels\Page;

class ExampleController extends Controller
{
    private $exampleVars;

    public function __construct()
    {
        $this->exampleVars = [
            'title' => 'Welcome Home',
            'text' => 'An inspiring quote here'
        ];
    }

    public function showPage(): Responsable
    {
        // Creating and returning a ViewModel instance
        return Page::create($this->exampleVars);
    }
}
```

### Advanced Usage

[](#advanced-usage)

#### Responsable Interface

[](#responsable-interface)

ViewModels implement Laravel's **Responsable** interface, allowing them to be directly returned from controller methods. Depending on the request's **acceptable content types**, the response can be either the **rendered view or a JSON representation**.

To force a response type, you can use methods like render() or toJson(). To add more acceptable content types (for example pdf), use ViewModel::macro() in conjunction with Laravel Request::macro() and Response::macro().

#### Usefull Methods

[](#usefull-methods)

- **\_\_toString():** Automatically renders the view when the ViewModel is treated as a string.
- **toArray():** Returns an array representation of the ViewModel, useful for formating the structure of the JSON responses.
- **toJson():** Returns a JSON string representation of the ViewModel.

#### Nesting ViewModels

[](#nesting-viewmodels)

That is totally doable...

```
$userWidget = UserWidget::create([
    'profile' => UserProfile::create(),
    'activity' => UserActivity::create(['activities' => $user->activities])
]);
```

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~111 days

Total

5

Last Release

1579d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7fb9da5a15010d335622bf9f465a32ef79c8d1cffcd139c2a9114736b72e2c13?d=identicon)[jdu](/maintainers/jdu)

---

Top Contributors

[![judus](https://avatars.githubusercontent.com/u/1478654?v=4)](https://github.com/judus "judus (8 commits)")

---

Tags

laravelview-model

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/maduser-laravel-viewmodel/health.svg)

```
[![Health](https://phpackages.com/badges/maduser-laravel-viewmodel/health.svg)](https://phpackages.com/packages/maduser-laravel-viewmodel)
```

###  Alternatives

[itstructure/laravel-grid-view

Grid view for laravel framework

2546.6k2](/packages/itstructure-laravel-grid-view)[ycs77/inertia-laravel-ssr-head

Simple SSR Head for Inertia Laravel

3211.5k](/packages/ycs77-inertia-laravel-ssr-head)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
