1. Go to this page and download the library: Download spatie/laravel-view-models library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
spatie / laravel-view-models example snippets
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();
}
}
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);
}
}
class PostViewModel extends ViewModel
{
protected $ignore = ['ignoredMethod'];
// …
public function ignoredMethod() { /* … */ }
}
class PostsController
{
public function update(Request $request, Post $post)
{
// …
return new PostViewModel($post);
}
}
class PostsController
{
public function update(Request $request, Post $post)
{
// …
return (new PostViewModel($post))->view('post.form');
}
}
class PostViewModel extends ViewModel
{
public function formatDate(Carbon $date): string
{
return $date->format('Y-m-d');
}
}