Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created July 11, 2024 17:47
Show Gist options
  • Save james2doyle/7c24000e9a9d4e7fec8de6e28e68d8c7 to your computer and use it in GitHub Desktop.
Save james2doyle/7c24000e9a9d4e7fec8de6e28e68d8c7 to your computer and use it in GitHub Desktop.
Merge attributes with props in a Laravel class component
<?php
namespace App\View\Components;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Card extends Component
{
public function __construct(
public array $title,
) {}
public function render(): View|Closure|string
{
return function (array $data) {
// replace the instance of the current attributes
$data['attributes'] = $data['attributes']->merge([
'title' => $this->title,
]);
// now we can apply the new attributes - this must be called even after manipulating $data
$this->withAttributes($data['attributes']->all());
return view('components.card', $data);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment