Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a controller function inside a view in laravel 5

Tags:

In laravel 4 i just used a function

$varbl = App::make("ControllerName")->FunctionName($params);

to call a controller function from a my balde template(view page). Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors. Is there any method to call a controller function from a view page in Laravel 5?

like image 907
Vishal Avatar asked Feb 11 '16 07:02

Vishal


People also ask

How do you call a controller inside a view in Laravel 7?

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.

How do you call a page with a controller in Laravel?

run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model. or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a static function .

Can we call function from another controller in Laravel?

Laravel gives you lots of other other options too i.e. event, jobs, model oberservers etc. If you have two controllers that need to perform the same functionality, then one option is to use a trait which you can then include in both controllers. But you should never need to transfer from one controller to another.


2 Answers

Just try this in your view :

{{ ControllerName::Functionname($params); }}

OR

<?php echo ControllerName::Functionname($params);?>

Refer this : http://laravel.io/forum/03-06-2014-what-is-the-proper-way-to-call-controllers-from-the-view?page=1

like image 137
Mr. Engineer Avatar answered Sep 28 '22 23:09

Mr. Engineer


If you have a function which is being used at multiple places you should define it in helpers file, to do so create one (may be) in app/Http/Helpers folder and name it helpers.php, mention this file in the autoload block of your composer.json in following way :

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Http/Helpers/helpers.php"
    ]
},

run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model.

or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a static function. Create.

public static function funtion_name($args) {}

Call.

\App\Http\Controllers\ControllerName::function_name($args)

If you don't like the very long code, you can just make it

ControllerName::function_name($args)

but don't forget to call it from the top of the view page.

use \App\Http\Controllers\ControllerName;
like image 31
Khan Shahrukh Avatar answered Sep 28 '22 22:09

Khan Shahrukh