Created
July 11, 2024 17:47
-
-
Save james2doyle/7c24000e9a9d4e7fec8de6e28e68d8c7 to your computer and use it in GitHub Desktop.
Merge attributes with props in a Laravel class component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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