Reputation: 199
I want to call an external function from my blade view.
I have tried in this way,
{{ controllername::function name()}}
But i get a response like Class 'controllername' not found.
How i can solve this?Looking for a solution.
Upvotes: 0
Views: 1222
Reputation: 182
In addition to above response. Just to correct your approach.
//include the controller class in to your blade file.
<?php use App\Http\Controllers\MyController;?>
//call the controller function in php way.
<?php echo MyController::myFunction(); ?>
// Or call the controller function in blade way.
{{MyController::myFunction()}}
We first map the controller in our blade file and call controller function from view in. We just make a static function in our controller class and calling in the static function.
Upvotes: 0
Reputation: 7334
If you are on Laravel 5.5, there is a way to do that using Service Injection. A verbatim copied example from the doc:
@inject('metrics', 'App\Services\MetricsService')
<div>
Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>
If you are not Using L5.5, then you can /Use/The/Path/OfTheClass
, so that the example above will be:
<div>
Monthly Revenue: {{ \App\Services\MetricsService::monthlyRevenue() }}.
</div>
Beware that, in this case
monthlyRevenue()
has to be a static function, which is sensible.
Otherwise, its much advisable to ensure the function that returns your view already did the work you need in theFunction()
and then pass it as value to the view directly.
Also Its hard to understand why you'll need your controller function in your view in the first place. Perhaps you need to check if your are not doing something wrong.
Upvotes: 2
Reputation: 1213
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 autorun 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;
Upvotes: 2