Start a Project

What is view model package ? How does it work ? How to use it ?

Introduction

The laravel view model is a laravel package created by Brent Roose. This package can move the work into a “view model” that you might do inside a controller. The main objective of this view model is that it is designed to house the complex logic of your views and clean up view-related logic from controllers.

For instance: 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.

How does it work ?

Create a  postViewModel class extending the main ViewModel class.

Now, the above class will get credited in to your controller.

They altogether (Model view and Controller) provide your view with the following abilities.

This package acts as the abstraction to the logic of your view.
How ?
Well, instead of passing the view model to the view, you can return a view directly like this.

Also, the function which requires extra parameters can be exposed

Which you can then reference in your template:

Refrences

Github Repository: https://github.com/spatie/laravel-view-models
Laravel News: https://laravel-news.com/laravel-view-models

Exit mobile version