All Projects → spatie → Laravel View Models

spatie / Laravel View Models

Licence: mit
View models in Laravel

Projects that are alternatives of or similar to Laravel View Models

Laravel Guided Image
Simplified and ready image manipulation for Laravel through intervention image.
Stars: ✭ 32 (-95.57%)
Mutual labels:  laravel, view
Laravel Tag Helper
Add powerful HTML tag helpers to your Laravel application
Stars: ✭ 227 (-68.56%)
Mutual labels:  laravel, view
Lvartisan
Laravel artisan command for creating view.
Stars: ✭ 18 (-97.51%)
Mutual labels:  laravel, view
Ardent
Self-validating, secure and smart models for Laravel's Eloquent ORM
Stars: ✭ 1,412 (+95.57%)
Mutual labels:  models, laravel
Bladeone
The standalone version Blade Template Engine without Laravel in a single php file and without dependencies
Stars: ✭ 411 (-43.07%)
Mutual labels:  laravel, view
Laravel Blade X
Use custom HTML components in your Blade views
Stars: ✭ 538 (-25.48%)
Mutual labels:  laravel, view
Log Viewer
Log viewer for laravel
Stars: ✭ 108 (-85.04%)
Mutual labels:  laravel, view
Laravel Model Caching
Eloquent model-caching made easy.
Stars: ✭ 1,829 (+153.32%)
Mutual labels:  models, laravel
Laravel Model Cleanup
Clean up unneeded records
Stars: ✭ 388 (-46.26%)
Mutual labels:  models, laravel
Laravel Blade Javascript
A Blade directive to export variables to JavaScript
Stars: ✭ 485 (-32.83%)
Mutual labels:  laravel, view
Blade
🔪 A standalone version of Laravel's Blade templating engine for use outside of Laravel.
Stars: ✭ 542 (-24.93%)
Mutual labels:  laravel, view
Artisan View
👀 Manage your views in Laravel projects through artisan
Stars: ✭ 708 (-1.94%)
Mutual labels:  laravel
Numberanimtextview
😿 数字增加和减小动画 TextView
Stars: ✭ 684 (-5.26%)
Mutual labels:  view
Laravel Media Manager
A "Vuejs & Laravel" Media Manager With Tons of Features
Stars: ✭ 684 (-5.26%)
Mutual labels:  laravel
Laravel Terminal
Runs artisan command in web application
Stars: ✭ 682 (-5.54%)
Mutual labels:  laravel
Laravel Elasticsearch
An easy way to use the official Elastic Search client in your Laravel applications.
Stars: ✭ 717 (-0.69%)
Mutual labels:  laravel
Laravel Boilerplate
Laravel Boilerplate / Starter Kit with Gentelella Admin Theme
Stars: ✭ 704 (-2.49%)
Mutual labels:  laravel
Laravel Heyman
Declarative style of authorization and validation in laravel.
Stars: ✭ 677 (-6.23%)
Mutual labels:  laravel
Invoiceninja
Invoices, Expenses and Tasks built with Laravel and Flutter
Stars: ✭ 6,247 (+765.24%)
Mutual labels:  laravel
Laravel Best Practices
Laravel best practices
Stars: ✭ 7,066 (+878.67%)
Mutual labels:  laravel

View models in Laravel

Latest Version on Packagist GitHub Workflow Status Total Downloads

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.

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.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

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. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-view-models

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 $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();
    }
}

And used in controllers like so:

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:

<input type="text" value="{{ $post->title }}" />
<input type="text" value="{{ $post->body }}" />

<select>
    @foreach ($categories as $category)
        <option value="{{ $category->id }}">{{ $category->name }}</option>
    @endforeach
</select>

<a href="{{ $indexUrl }}">Back</a>

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

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

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

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

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].