Call controller function from view in laravel 5

This is not a proper way to code but sometime we have requirements to call controller function from view. So let’s see how we can call controller function from view in laravel 5. First we need a controller function. So let first create a controller.

Controller

Create a laravel 5 controller under app/Http/Controllers/MyController.php and add a static function which we will call from view. Function must be a static type function.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class MyController extends Controller
{ 
	public static function my($args){
		// do your stuff or return something.
		echo $args."I am called on view.";
	}
}

Call controller function from view

So we created a static function in our controller let create a laravel 5 view under resources/views/my.blade.php and call our controller function.

//include the controller class.
<?php use App\Http\Controllers\MyController;?>
//call the controller function in php way with passing args.
<?php echo MyController::my('hello'); ?>
// Or call the controller function in blade way.
{{MyController::my('hello')}}

So this is the way to call controller function from view in laravel 5. We just make a static function in our controller class and calling in static function call way.

Cheerss! happy coding!

Adam Brown
Please follow and like us:

Leave a Comment