Using controller function directly in Laravel blade

Today I would like to talk about using the function from controller directly on your blade view files.

Normally we wrote codes relating with application logic and database and then pass the data to specific view files. But what if we like to use the function from controller directly ?

We can create a static function in controller and then can directly be called from blade file without instantiating the class. Let me write a sample example.

Firstly, we will create a static function in controller. Why static function ?

If we create a normal function, we will need to instantiate the class in view file like this `new Controller()` which will be a mess in view files. Static function can be directly called using scope resolution (::) operator.

<?php

namespace App\Http\Controllers;

class HomeController extends Controller
{
    public static function greet() 
    {
        return "Hello World";
    }
}

After that we can call the above controller function directly by providing the namespace of the controller and function using scope resolution operator like this.

<p>                                    
{{ App\Http\Controllers\HomeController::greet() }}
<!-- output - Hello World -->
</p>

By Yuuma



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム