1class PostViewModel extends ViewModel
2{
3 protected $ignore = ['ignoredMethod'];
4
5 // …
6
7 public function ignoredMethod() { /* … */ }
8}
1class PostViewModel extends ViewModel
2{
3 public $indexUrl = null;
4
5 public function __construct(User $user, Post $post = null)
6 {
7 $this->user = $user;
8 $this->post = $post;
9
10 $this->indexUrl = action([PostsController::class, 'index']);
11 }
12
13 public function post(): Post
14 {
15 return $this->post ?? new Post();
16 }
17
18 public function categories(): Collection
19 {
20 return Category::canBeUsedBy($this->user)->get();
21 }
22}
1class PostsController
2{
3 public function update(Request $request, Post $post)
4 {
5 // …
6
7 return new PostViewModel($post);
8 }
9}
1<input type="text" value="{{ $post->title }}" />
2<input type="text" value="{{ $post->body }}" />
3
4<select>
5 @foreach ($categories as $category)
6 <option value="{{ $category->id }}">{{ $category->name }}</option>
7 @endforeach
8</select>
9
10<a href="{{ $indexUrl }}">Back</a>
1class PostViewModel extends ViewModel
2{
3 public function formatDate(Carbon $date): string
4 {
5 return $date->format('Y-m-d');
6 }
7}
1class PostsController
2{
3 public function create()
4 {
5 $viewModel = new PostViewModel(
6 current_user()
7 );
8
9 return view('blog.form', $viewModel);
10 }
11
12 public function edit(Post $post)
13 {
14 $viewModel = new PostViewModel(
15 current_user(),
16 $post
17 );
18
19 return view('blog.form', $viewModel);
20 }
21}