Skip to content

Instantly share code, notes, and snippets.

@JunaidQadirB
Created October 14, 2022 20:11
Show Gist options
  • Save JunaidQadirB/157d1f2dd42b896514da0fca63846e73 to your computer and use it in GitHub Desktop.
Save JunaidQadirB/157d1f2dd42b896514da0fca63846e73 to your computer and use it in GitHub Desktop.
<?php
// UserViewModel.php
class UserViewModel extends ViewModel
{
public User $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function statuses(): array
{
return UserStatus::all()->map(function ($status) {
return [
'text' => $status->name,
'value' => $status->id,
];
})->toArray();
}
}
// UserController.php
class UserController
{
public function create()
{
return view('users.create', new UserViewModel(new User()));
}
public function edit(User $user)
{
return view('users.edit', new UserViewModel($user));
}
}
// Usage of statuses in the form
// edit.blade.php
@component('components.themes.default.select',[
'label' => 'Status',
'name' => 'status_id',
'value' => old('status_id', $user->status_id),
'options' => $statuses,
'optionValueKey' => 'value',
'optionTextKey' => 'text'
])@endcomponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment