How view models work in Laravel
mainA view model is a class used to transform data and encapsulate complex logic required by a view, making controllers lighter.
To create one, extend Spatie\ViewModels\ViewModel. All public properties and methods are automatically exposed to the view.
Key Behaviors:
- Automatic Exposure: Any public property or method can be accessed directly in Blade using the variable name (e.g.,
$propertyor$method()). - Ignoring Methods: If you want to prevent a public method from being accessible in the view, add its name to the
$ignoreprotected property. - Function Arguments: You can expose methods that require parameters. In Blade, these are called using the syntax
{{ $methodName($argument) }}. - Magic Methods: PHP's built-in magic methods are automatically ignored and not exposed to the view.
class PostViewModel extends ViewModel
{
protected $ignore = ['ignoredMethod'];
public $post;
public function __construct(Post $post)
{
$this->post = $post;
}
public function ignoredMethod() { /* Not available in view */ }
public function formatDate(\Carbon $date): string
{
return $date->format('Y-m-d');
}
}