DEV Community

Cover image for Laravel 7: Functions in Blade Components
Zubair Mohsin
Zubair Mohsin

Posted on

Laravel 7: Functions in Blade Components

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

Let me know in comments how you can use this feature 👇🏼

Top comments (1)

Collapse
 
eimkasp profile image
Eimantas

Wow, thanks for an article! 1st answer to this on google and syntax is not something you can guess on this part!