Sometimes you want to use the HTML output from a blade component in a PHP class. You can do this using the view('component')->render()
method. For example:
Let’s say we had a component which was constructed as:
<?php
namespace App\View\Components\Show;
use Illuminate\View\Component;
class VisibilityIcon extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct(
public string $visibility,
public bool $asSpan = false
) {
//
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.show.visibility-icon');
}
}
PHPTo use it we would need to use it as so:
$htmlOutput = view('components.show.visibility-icon',
[
'visibility' => $visibility,
'asSpan' => false // needs explicit definition as view()->render() does not construct
]
)->render();
PHPNote: You need to explicitly define 'asSpan'
when calling the view()
even though it there are defaults defined in the component constructor. This is because when you render the component directly through the view()
function, the constructor of the component class is not called, and thus the default value is not set.