PHPackages                             spatie/laravel-view-models - 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. spatie/laravel-view-models

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

spatie/laravel-view-models
==========================

View models in Laravel

1.6.2(2mo ago)1.1k3.5M—6.4%6014MITPHPPHP ^7.3|^8.0CI passing

Since Sep 12Pushed 2mo ago18 watchersCompare

[ Source](https://github.com/spatie/laravel-view-models)[ Packagist](https://packagist.org/packages/spatie/laravel-view-models)[ Docs](https://github.com/spatie/laravel-view-models)[ Fund](https://spatie.be/open-source/support-us)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-laravel-view-models/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (22)Used By (14)

View models in Laravel
======================

[](#view-models-in-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/920ce180dd3b490c984a779b1a5836ab4dbecce892e01b0e0560cb002069066f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d766965772d6d6f64656c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-view-models)[![GitHub Workflow Status](https://camo.githubusercontent.com/a46dc378f8b91ed0710af733e3bece1977d526b70f50006649bdc4fb7edb9e89/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6c61726176656c2d766965772d6d6f64656c732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d5465737473267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/a46dc378f8b91ed0710af733e3bece1977d526b70f50006649bdc4fb7edb9e89/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6c61726176656c2d766965772d6d6f64656c732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d5465737473267374796c653d666c61742d737175617265)[![Total Downloads](https://camo.githubusercontent.com/d700e527b0675a62eb757258b9be88281aa55f16ad68d862663a3dcb4b9ec3e1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d766965772d6d6f64656c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-view-models)

Have you ever made a controller where you had to do a lot of work to prepare variables to be passed to a view? You can move that kind of work to a so called view model. In essence, view models are simple classes that take some data, and transform it into something usable for the view.

You'll find a more detailed explanation and some good examples in [this blogpost on Stitcher.io](https://stitcher.io/blog/laravel-view-models).

Laravel's native view composers are not the same as the view models provided by this package. To learn more about the differences head over to [this blogpost on Stitcher.io](https://stitcher.io/blog/laravel-view-models-vs-view-composers).

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/1b672f6dfcfcc145af22375dc20813952b8d140bc191403d8938719f36ef06b2/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d766965772d6d6f64656c732e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-view-models)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-view-models
```

Usage
-----

[](#usage)

A view model is a class where you can put some complex logic for your views. This will make your controllers a bit lighter. You can create a view model by extending the provided `Spatie\ViewModels\ViewModel`.

```
class PostViewModel extends ViewModel
{
    public $user;

    public $post;

    public $indexUrl = null;

    public function __construct(User $user, Post $post = null)
    {
        $this->user = $user;
        $this->post = $post;

        $this->indexUrl = action([PostsController::class, 'index']);
    }

    public function post(): Post
    {
        return $this->post ?? new Post();
    }

    public function categories(): Collection
    {
        return Category::canBeUsedBy($this->user)->get();
    }
}
```

Then you can use the view model class in your controller like this:

```
class PostsController
{
    public function create()
    {
        $viewModel = new PostViewModel(
            current_user()
        );

        return view('blog.form', $viewModel);
    }

    public function edit(Post $post)
    {
        $viewModel = new PostViewModel(
            current_user(),
            $post
        );

        return view('blog.form', $viewModel);
    }
}
```

In a view you can do this:

```

    @foreach ($categories as $category)
        {{ $category->name }}
    @endforeach

Back
```

All public methods and properties in a view model are automatically exposed to the view. If you don't want a specific method to be available in your view, you can ignore it.

```
class PostViewModel extends ViewModel
{
    protected $ignore = ['ignoredMethod'];

    // …

    public function ignoredMethod() { /* … */ }
}
```

All PHP's built in magic methods are ignored automatically.

#### View models as responses

[](#view-models-as-responses)

It's possible to directly return a view model from a controller. By default, a JSON response with the data is returned.

```
class PostsController
{
    public function update(Request $request, Post $post)
    {
        // …

        return new PostViewModel($post);
    }
}
```

This approach can be useful when working with AJAX submitted forms.

It's also possible to return a view directly:

```
class PostsController
{
    public function update(Request $request, Post $post)
    {
        // …

        return (new PostViewModel($post))->view('post.form');
    }
}
```

Note that when the `Content-Type` header of the request is set to JSON, this approach will also return JSON data instead of a rendered view.

#### Exposing view functions

[](#exposing-view-functions)

View models can expose functions which require extra parameters.

```
class PostViewModel extends ViewModel
{
    public function formatDate(Carbon $date): string
    {
        return $date->format('Y-m-d');
    }
}
```

You can use these functions in the view like so:

```
{{ $formatDate($post->created_at) }}
```

### Making a new view model

[](#making-a-new-view-model)

The package included an artisan command to create a new view model.

```
php artisan make:view-model HomepageViewModel
```

This view model will have the `App\ViewModels` namespace and will be saved in `app/ViewModels`.

or into a custom namespace, say, `App\Blog`

```
php artisan make:view-model "Blog/PostsViewModel"
```

This view model will have the `App\Blog\ViewModels` namespace and will be saved in `app/Blog/ViewModels`.

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

### Security

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Brent Roose](https://github.com/brendt)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

69

—

FairBetter than 100% of packages

Maintenance83

Actively maintained with recent releases

Popularity66

Solid adoption and visibility

Community38

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 51% 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 ~143 days

Recently: every ~279 days

Total

20

Last Release

86d ago

Major Versions

0.0.1 → 1.0.02018-09-12

1.3.2 → v2.x-dev2021-04-01

PHP version history (5 changes)0.0.1PHP ^7.1

1.3.0PHP ^7.2

1.3.1PHP ^7.3

1.3.2PHP ^7.3|^8.0

v2.x-devPHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (78 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (25 commits)")[![ijpatricio](https://avatars.githubusercontent.com/u/26031459?v=4)](https://github.com/ijpatricio "ijpatricio (8 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (7 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (6 commits)")[![alexmanase](https://avatars.githubusercontent.com/u/10696975?v=4)](https://github.com/alexmanase "alexmanase (6 commits)")[![JamesFreeman](https://avatars.githubusercontent.com/u/916500?v=4)](https://github.com/JamesFreeman "JamesFreeman (5 commits)")[![gjinali](https://avatars.githubusercontent.com/u/2167268?v=4)](https://github.com/gjinali "gjinali (3 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (3 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![bastien-phi](https://avatars.githubusercontent.com/u/10199039?v=4)](https://github.com/bastien-phi "bastien-phi (2 commits)")[![kadimi](https://avatars.githubusercontent.com/u/225615?v=4)](https://github.com/kadimi "kadimi (1 commits)")[![alexbowers](https://avatars.githubusercontent.com/u/842974?v=4)](https://github.com/alexbowers "alexbowers (1 commits)")[![mattdfloyd](https://avatars.githubusercontent.com/u/185187?v=4)](https://github.com/mattdfloyd "mattdfloyd (1 commits)")[![MaxGiting](https://avatars.githubusercontent.com/u/9828591?v=4)](https://github.com/MaxGiting "MaxGiting (1 commits)")[![shuvroroy](https://avatars.githubusercontent.com/u/21066418?v=4)](https://github.com/shuvroroy "shuvroroy (1 commits)")[![clovon](https://avatars.githubusercontent.com/u/64031139?v=4)](https://github.com/clovon "clovon (1 commits)")[![erikn69](https://avatars.githubusercontent.com/u/4933954?v=4)](https://github.com/erikn69 "erikn69 (1 commits)")[![jdrieghe](https://avatars.githubusercontent.com/u/12606789?v=4)](https://github.com/jdrieghe "jdrieghe (1 commits)")

---

Tags

laravelmodelsphpviewspatielaravel-view-models

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/spatie-laravel-view-models/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-view-models/health.svg)](https://phpackages.com/packages/spatie-laravel-view-models)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M2.6k](/packages/craftcms-cms)[spatie/laravel-blade-javascript

A Blade directive to export variables to JavaScript

638855.8k9](/packages/spatie-laravel-blade-javascript)[robsontenorio/mary

Gorgeous UI components for Livewire powered by daisyUI and Tailwind

1.5k454.7k15](/packages/robsontenorio-mary)[livewire/blaze

A tool for optimizing Blade component performance by folding them into parent templates

688221.3k17](/packages/livewire-blaze)[spatie/commonmark-shiki-highlighter

Highlight code blocks with league/commonmark and Shiki

893.5M9](/packages/spatie-commonmark-shiki-highlighter)[spatie/laravel-blade-comments

Add debug comments to your rendered output

177325.5k](/packages/spatie-laravel-blade-comments)

PHPackages © 2026

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