Using controller function directly in Laravel blade
- 2021年1月12日
- 技術情報
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
yuuma at 2021年01月12日 10:00:59