maduser/laravel-viewmodel is a Laravel package for viewmodels for laravel.
It currently has 0 GitHub stars and 4 downloads on Packagist (latest version 1.0.4).
Install it with composer require maduser/laravel-viewmodel.
Discover more Laravel packages by maduser
or browse all Laravel packages to compare alternatives.
Last updated
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.
Install the package via composer:
composer require maduser/laravel-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;
}
}
Create a corresponding Blade template for your ViewModel. For the MyQuoteWidget ViewModel, the my-widget.blade.php file might look like this:
<div class="widget quote">
<p>{{ $view->getQuote() }}</p>
</div>
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);
}
}
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().
That is totally doable...
$userWidget = UserWidget::create([
'profile' => UserProfile::create(),
'activity' => UserActivity::create(['activities' => $user->activities])
]);