How to call controller function from view in Laravel

You can call controller function from view in Laravel by defining the controller method as a static method and call the method from view file by specifying the full path of controller class.

Answers 1
  • Get user details by calling controller's method from view in Laravel

    //resources\views\home.blade.php
    @php echo App\Http\Controllers\HomeController::getUserByID(1);  @endphp
    
    //app\Http\Controllers\HomeController.php
    //Create controller (HomeController) if not already created using php artisan make:controller HomeController and use below function in it.
    public static function getUserByID($id){
        $user = User::findOrFail($id);
        return $user;
    }
    
    0

    Output:

    {"id":1,"name":"john","email":"[email protected]","email_verified_at":"2021-08-02T00:38:40.000000Z",
    "created_at":"2021-08-02T00:38:40.000000Z","updated_at":"2021-08-02T00:38:40.000000Z"}

    This code snippet helps you to call the controller's method from view file. You have to create a web route, a function with static method in controller and you can call this method from view file by specifying the full path of controller class by passing argument to controller's method.

  • Back to code snippet queries related laravel