With Laravel 7 Blade Components, you can invoke public functions in view file of Component. Let's look into good old Alert
component example.
class Alert extends Component
{
public string $type;
public string $message;
public function __construct(string $type, string $message)
{
$this->type = $type;
$this->message = $message;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.alert');
}
}
Now, let's add a function/method customFunction in our class as:
class Alert extends Component
{
public string $type;
public string $message;
public function __construct(string $type, string $message)
{
$this->type = $type;
$this->message = $message;
}
public function customFunction(): string
{
return "string from a custom function component";
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.alert');
}
}
Invoking the function
Now let's say we want to use this method inside the alert.blade.php
. It's as easy as using a public property
in component's view file.
<div>
<div class="alert alert-{{$type}}">
<h3>{{$message}}</h3>
<span>{{ $customFunction }}</span>
</div>
</div>
Passing parameters
What if we needed to pass some parameters? Easy ð
<div>
<div class="alert alert-{{$type}}">
<h3>{{$message}}</h3>
<span>{{ $customFunction('custom param') }}</span>
</div>
</div>
and in our class file:
class Alert extends Component
{
public string $type;
public string $message;
public function __construct(string $type, string $message)
{
$this->type = $type;
$this->message = $message;
}
public function customFunction(string $param): string
{
return "string from a custom function component and a " . $param;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.alert');
}
}
Let me know in comments how you can use this feature ððŒ
Top comments (1)
Wow, thanks for an article! 1st answer to this on google and syntax is not something you can guess on this part!