I have a blade component called OrderBox.php in app/View/Components. It has several public attributes I can access from the orderbox.blade.php template file.
<x-orderbox
:id="$id"
....
></x-orderbox>
However, there is a public function getShortTextByStatus($statusCode) in the OrderBox.php component file
and when I call this function inside orderbox.blade.php template
{{ $getShortTextByStatus('EDIT') }}
I get the Undefined variable: shortTextByStatus error
I followed this: https://laravel.com/docs/8.x/blade#component-methods but everything looks the same, what am I missing?
EDIT:
If I remove the $ I get the Call to undefined function getShortTextByStatus() error
{{ getShortTextByStatus('EDIT') }}
OrderBox.php
class OrderBox extends Component
{
public $id;
....
public function __construct()
{
//
}
public function render()
{
return view('components.orderbox');
}
public function getShortTextByStatus($statusCode)
{
return 'TEST';
}
}
EDIT 2:
I noticed that x-orderbox actually should be x-order-box
<x-order-box
:id="$id"
....
></x-order-box>
With this, the {{ $getShortTextByStatus("EDIT") }} works !
B U T
does not pass attributes like :id="$id" or
something="static"
So the public $id; or public $something will be empty....
So I made a couple of mistakes here
First of all, if the component name is OrderBox than the
tag should be
<x-order-box></x-order-box>
And then, if you want to pass data to the component (OrdeBox) you need to add the attributes to the constructor - special thanks to @gert-b (Gert B) from the comment section
class OrderBox extends Component
{
public $id;
public $otherId;
....
public function __construct($id, $otherId)
{
$this->id = $id;
$this->otherId;
}
...
...
}
For some reason, I thought only mandatory attributes go to the constructor.
And don't forget, the attributes in the component class are camelCase like public $otherId; but in the template, it is kebab case: other-id
<x-order-box
id="1"
:other-id="$someVariable"
></x-order-box>