How to Call Controller Function in Blade Laravel?

By Hardik Savani September 2, 2022 Category : Laravel

Hey Friends,

I will explain step by step tutorial how to call controller function in blade laravel. This tutorial will give you a simple example of laravel call controller method from view. I’m going to show you about laravel call controller function from blade. This article goes in detailed on how to call function in blade laravel.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

Sometimes, we need to call the controller function in the blade file. But if you need to call a function in the blade file then you can also use helper functions. I will give you two following ways to call a function in the blade file.

1) Using Controller Static Method

2) Using Custom Helper Functions(recommended)

The second option I will highly recommend.

So, let's see both examples with output.

Example 1: Using Controller Static Method

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

return view('posts');

}

/**

* Write code on Method

*

* @return response()

*/

public static function moneyFormat($amount)

{

return '$' . number_format($amount, 2);

}

}

resources/views/posts.blade.php

<!DOCTYPE html>

<html>

<head>

<title>How to Call Controller Function in Blade Laravel? - ItSolutionStuff.com</title>

</head>

@php

$money = App\Http\Controllers\PostController::moneyFormat(12000);

@endphp

<body>

<p>{{ $money }}</p>

</body>

</html>

Output:

$12,000.00

Example 2: Using Custom Helper Functions(recommended)

In this step, you need to create app/Helpers/helpers.php in your laravel project and put the following code in that file:

app/Helpers/helpers.php

<?php

/**

* Write code on Method

*

* @return response()

*/

if (! function_exists('moneyFormat')) {

function moneyFormat($amount)

{

return '$' . number_format($amount, 2);

}

}

Next, you have to put path of helpers file,so basically open composer.json file and put following code in that file:

composer.json

...

"autoload": {

"psr-4": {

"App\\": "app/",

"Database\\Factories\\": "database/factories/",

"Database\\Seeders\\": "database/seeders/"

},

"files": [

"app/Helpers/helpers.php"

]

},

...

After register, we need to run composer auto load command so that will load our helper file.

next run bellow command:

composer dump-autoload

Next, you can use helper function in blade file as like the below:

resources/views/posts.blade.php

<!DOCTYPE html>

<html>

<head>

<title>How to Call Controller Function in Blade Laravel? - ItSolutionStuff.com</title>

</head>

<body>

<p>{{ moneyFormat(12000) }}</p>

</body>

</html>

Output:

$12,000.00

I hope it can help you...

Tags :