Директива props
Директива props применяется в классах компонентов Laravel для объявления доступных свойств. Она позволяет определить список атрибутов, которые компонент может принимать, с возможностью указания их типов, значений по умолчанию и правил валидации. Это делает компоненты более надёжными и самодокументируемыми.
Директива используется внутри метода render класса компонента или в самом классе через свойство $props. Она автоматически связывает публичные свойства класса с атрибутами, переданными в компонент при его вызове.
Синтаксис
<?php
use IlluminateViewComponent;
class Alert extends Component
{
public $type;
public $message;
public $dismissible = false;
public function __construct($type, $message, $dismissible = false)
{
$this->type = $type;
$this->message = $message;
$this->dismissible = $dismissible;
}
public function render()
{
return view('components.alert');
}
}
?>
Пример
Давайте создадим компонент для вывода сообщений с различными типами:
<?php
namespace AppViewComponents;
use IlluminateViewComponent;
use IlluminateViewComponentAttributeBag;
class Alert extends Component
{
public $type;
public $message;
public $dismissible;
public function __construct($type = 'info', $message, $dismissible = false)
{
$this->type = $type;
$this->message = $message;
$this->dismissible = $dismissible;
}
public function render()
{
return view('components.alert');
}
}
?>
<div class="alert alert-{{ $type }}">
@if ($dismissible)
<button type="button" class="close" data-dismiss="alert">×</button>
@endif
{{ $message }}
</div>
Теперь используем компонент в представлении:
<x-alert type="success" message="Operation completed successfully!" />
<x-alert type="danger" message="An error occurred" dismissible="true" />
Результат выполнения кода:
"<div class="alert alert-success">Operation completed successfully!</div>"
"<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">×</button>An error occurred</div>"
Пример
Пример компонента для отображения пользовательской карточки с использованием типизированных свойств:
<?php
namespace AppViewComponents;
use IlluminateViewComponent;
use IlluminateViewComponentAttributeBag;
class UserCard extends Component
{
public string $name;
public string $email;
public ?string $avatar = null;
public bool $active = true;
public function __construct(string $name, string $email, ?string $avatar = null, bool $active = true)
{
$this->name = $name;
$this->email = $email;
$this->avatar = $avatar;
$this->active = $active;
}
public function render()
{
return view('components.user-card');
}
}
?>
<div class="user-card @if($active) active @else inactive @endif">
@if($avatar)
<img src="{{ $avatar }}" alt="{{ $name }}" class="avatar">
@endif
<h3>{{ $name }}</h3>
<p>{{ $email }}</p>
<span class="status">{{ $active ? 'Active' : 'Inactive' }}</span>
</div>
Использование компонента:
<x-user-card
name="John Doe"
email="john@example.com"
avatar="/images/john.jpg"
:active="true"
/>
<x-user-card
name="Jane Smith"
email="jane@example.com"
:active="false"
/>
Результат выполнения кода:
"<div class="user-card active"><img src="/images/john.jpg" alt="John Doe" class="avatar"><h3>John Doe</h3><p>john@example.com</p><span class="status">Active</span></div>"
"<div class="user-card inactive"><h3>Jane Smith</h3><p>jane@example.com</p><span class="status">Inactive</span></div>"
Пример
Пример компонента для отображения списка элементов с использованием коллекции:
<?php
namespace AppViewComponents;
use IlluminateViewComponent;
use IlluminateSupportCollection;
class ItemList extends Component
{
public Collection $items;
public string $title;
public bool $ordered;
public function __construct(Collection $items, string $title = 'Items', bool $ordered = false)
{
$this->items = $items;
$this->title = $title;
$this->ordered = $ordered;
}
public function render()
{
return view('components.item-list');
}
}
?>
<div class="item-list">
<h4>{{ $title }}</h4>
@if($ordered)
<ol>
@foreach($items as $item)
<li>{{ $item }}</li>
@endforeach
</ol>
@else
<ul>
@foreach($items as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
@endif
</div>
Использование компонента в контроллере:
<?php
namespace AppHttpControllers;
use AppViewComponentsItemList;
use IlluminateSupportCollection;
class ItemController extends Controller
{
public function index()
{
$items = new Collection(['item 1', 'item 2', 'item 3', 'item 4', 'item 5']);
return view('items', ['items' => $items]);
}
}
?>
<x-item-list :items="$items" title="My Items" :ordered="true" />
Результат выполнения кода:
"<div class="item-list"><h4>My Items</h4><ol><li>item 1</li><li>item 2</li><li>item 3</li><li>item 4</li><li>item 5</li></ol></div>"