Laravel custom view helpers stop working when using namespace
I followed some tutorials to create some global helper functions to be used as blades.
I created a ViewHelpers.php file in the App \ Helpers folder. This file contains the following code:
<?php
class ViewHelpers {
public static function bah()
{
echo 'blah';
}
}
Here is my service provider that downloads my helpers (currently only one file):
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider {
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
echo $filename; // for debugging - yes, I see it is getting called
require_once($filename);
}
}
}
I added it to config \ app.php under "providers":
'App\Providers\HelperServiceProvider',
And now I call my blade helper:
{{ViewHelpers::bah()}}
So far it works fine.
But if I change the ViewHelper namespace to this:
<?php namespace App\Helpers;
class ViewHelpers {
// omitted for brevity
my views fail with Class 'ViewHelpers' not found
.
How do I make my views view the ViewHelpers class even if it's in a different namespace? Where can I add use App\Helpers
?
Another related question - can I alias the ViewHelpers class so that it looks like, say, VH:bah()
in my views?
And I would rather do it in a simple way if possible (no facades and what not), because these are just static helpers, no need for a class instance and IoC.
I am using Laravel 5.
source to share
You will get Class 'ViewHelpers' not found
because no ViewHelpers
, there is App\Helpers\ViewHelpers
, and you need to specify the namespace (even in the view).
You can register an alias in config/app.php
, which will allow you to use VH::something()
:
'aliases' => [
// in the end just add:
'VH' => 'App\Helpers\ViewHelpers'
],
If your namespace is correct, you don't even need to use providers - the class will be loaded by Laravel.
source to share