php artisan make:component ComponentName
creates
ComponentName.blade.php
inside
resources/view/components
and controller
ComponentName.php
inside
App\View\Component
directory
you can render component by
x-
syntax
<x-component-name />
pass variables to components
use
var-name=
for normal strings and use
:var-name=
for variables
<x-component-name var-name="normal string" :var-name2="$some_variable"/>
make sure to use
kebab-case
as html attribute names and
camelCase
inside constructor argument
and inside component controller file
ComponentName.php
namespace App\View\Components;
use Illuminate\View\Component;
class ComponentName extends Component
{
public $varName1;
public $varName2;
public function __construct($varName1, $varName2)
{
$this->varName1 = $varName1;
$this->varName2 = $varName2;
}
public function customFunction($last)
{
return [1, 2, 3, 4, 5, 6, 7, $last]; // or data from db for example
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|\Closure|string
*/
public function render()
{
return view('components.component_name');
}
}
inside
ComponentName.blade.php
we can retrieve these variables like so
<div class="component-class">
<div>{{$varName1}}</div>
<div>{{$varName2}}</div>
@foreach($customFunction('last line') as $line)
<h1>{{$line}}</h1>
@endforeach
</div>