{"id":13563988,"url":"https://github.com/spatie/laravel-view-models","last_synced_at":"2025-05-14T15:07:44.483Z","repository":{"id":32976468,"uuid":"147871189","full_name":"spatie/laravel-view-models","owner":"spatie","description":"View models in Laravel","archived":false,"fork":false,"pushed_at":"2024-03-13T18:00:53.000Z","size":111,"stargazers_count":1019,"open_issues_count":0,"forks_count":61,"subscribers_count":21,"default_branch":"main","last_synced_at":"2024-10-29T20:25:46.267Z","etag":null,"topics":["laravel","models","php","view"],"latest_commit_sha":null,"homepage":"https://spatie.be/open-source","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"spatie","custom":"https://spatie.be/open-source/support-us"}},"created_at":"2018-09-07T20:22:46.000Z","updated_at":"2024-10-29T19:12:36.000Z","dependencies_parsed_at":"2024-03-13T18:54:55.003Z","dependency_job_id":"7b147453-4606-43f9-9b04-e8bd1fb18a52","html_url":"https://github.com/spatie/laravel-view-models","commit_stats":{"total_commits":116,"total_committers":22,"mean_commits":"5.2727272727272725","dds":0.603448275862069,"last_synced_commit":"b4a8a2c4240cae3f8f3b3d53991c7abcbd75b3d1"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-view-models","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-view-models/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-view-models/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-view-models/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/laravel-view-models/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248813786,"owners_count":21165632,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["laravel","models","php","view"],"created_at":"2024-08-01T13:01:25.280Z","updated_at":"2025-04-14T02:57:45.479Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://github.com/sponsors/spatie","https://spatie.be/open-source/support-us"],"categories":["PHP"],"sub_categories":[],"readme":"# View models in Laravel\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-view-models.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-view-models)\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/spatie/laravel-view-models/run-tests.yml?branch=main\u0026label=Tests\u0026style=flat-square)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-view-models.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-view-models)\n\nHave 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.\n\nYou'll find a more detailed explanation and some good examples in [this blogpost on Stitcher.io](https://stitcher.io/blog/laravel-view-models).\n\nLaravel'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).\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/laravel-view-models.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/laravel-view-models)\n\nWe 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).\n\nWe 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).\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require spatie/laravel-view-models\n```\n\n## Usage\n\nA 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`.\n\n```php\nclass PostViewModel extends ViewModel\n{\n    public $user;\n\n    public $post;\n    \n    public $indexUrl = null;\n\n    public function __construct(User $user, Post $post = null)\n    {\n        $this-\u003euser = $user;\n        $this-\u003epost = $post;\n        \n        $this-\u003eindexUrl = action([PostsController::class, 'index']); \n    }\n    \n    public function post(): Post\n    {\n        return $this-\u003epost ?? new Post();\n    }\n    \n    public function categories(): Collection\n    {\n        return Category::canBeUsedBy($this-\u003euser)-\u003eget();\n    }\n}\n```\n\nThen you can use the view model class in your controller like this:\n\n```php\nclass PostsController\n{\n    public function create()\n    {\n        $viewModel = new PostViewModel(\n            current_user()\n        );\n        \n        return view('blog.form', $viewModel);\n    }\n    \n    public function edit(Post $post)\n    {\n        $viewModel = new PostViewModel(\n            current_user(), \n            $post\n        );\n    \n        return view('blog.form', $viewModel);\n    }\n}\n```\n\nIn a view you can do this:\n\n```blade\n\u003cinput type=\"text\" value=\"{{ $post-\u003etitle }}\" /\u003e\n\u003cinput type=\"text\" value=\"{{ $post-\u003ebody }}\" /\u003e\n\n\u003cselect\u003e\n    @foreach ($categories as $category)\n        \u003coption value=\"{{ $category-\u003eid }}\"\u003e{{ $category-\u003ename }}\u003c/option\u003e\n    @endforeach\n\u003c/select\u003e\n\n\u003ca href=\"{{ $indexUrl }}\"\u003eBack\u003c/a\u003e\n```\n\nAll 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.\n\n```php\nclass PostViewModel extends ViewModel\n{\n    protected $ignore = ['ignoredMethod'];\n\n    // …\n    \n    public function ignoredMethod() { /* … */ }\n}\n```\n\nAll PHP's built in magic methods are ignored automatically.\n\n#### View models as responses\n\nIt's possible to directly return a view model from a controller. \nBy default, a JSON response with the data is returned.\n\n```php\nclass PostsController\n{\n    public function update(Request $request, Post $post)\n    {\n        // …\n        \n        return new PostViewModel($post);\n    }\n}\n```\n\nThis approach can be useful when working with AJAX submitted forms.\n\nIt's also possible to return a view directly:\n\n```php\nclass PostsController\n{\n    public function update(Request $request, Post $post)\n    {\n        // …\n        \n        return (new PostViewModel($post))-\u003eview('post.form');\n    }\n}\n```\n\nNote that when the `Content-Type` header of the request is set to JSON, \nthis approach will also return JSON data instead of a rendered view.\n\n#### Exposing view functions\n\nView models can expose functions which require extra parameters.\n\n```php\nclass PostViewModel extends ViewModel\n{\n    public function formatDate(Carbon $date): string\n    {\n        return $date-\u003eformat('Y-m-d');\n    }\n}\n```\n\nYou can use these functions in the view like so:\n\n```blade\n{{ $formatDate($post-\u003ecreated_at) }}\n```\n\n### Making a new view model\n\nThe package included an artisan command to create a new view model.\n\n```bash\nphp artisan make:view-model HomepageViewModel\n```\n\nThis view model will have the `App\\ViewModels` namespace and will be saved in `app/ViewModels`.\n\nor into a custom namespace, say, `App\\Blog`\n\n```bash\nphp artisan make:view-model \"Blog/PostsViewModel\"\n```\n\nThis view model will have the `App\\Blog\\ViewModels` namespace and will be saved in `app/Blog/ViewModels`.\n\n### Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n### Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Credits\n\n- [Brent Roose](https://github.com/brendt)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-view-models","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Flaravel-view-models","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-view-models/lists"}