I have a helpers.php
file in the app
directory of my Laravel project. In this file, I have a function that checks if an item's image is in the storage file and if it isn't it replaces it with an image not found, here is the file:
function productImage($path)
{
return ($path != null) && file_exists('storage/' . $path) ? asset('storage/' . $path) : asset('img/error/img-not-found.jpg');
}
This is where it is called in one of my blade.php
files:
@foreach($products as $product)
<div class="product">
<a href="{{ route('shop.show', $product->slug) }}" class="linkToInfo">
<img src="{{ productImage($product->image) }}" alt="{{ $product->name }}" class="productImg">
<p class="productData">{{ $product->name }}</p>
<p class="productData">{{ $product->presentPrice() }}</p>
</a>
</div>
@endforeach
When I try and load this page tho, I get this error:
You need to either register (via alias) the class or instantiate it so that blade sees it when compiling.
Instantiate within blade :
{{ \App\Helpers::instance()->productImage($product->image) }}
Or, what I've done usually is to create an alias for your Helper class in config\app.php . This reduces a little overhead and typing as well.
Alias:
'aliases' => [
....
'Helpers' => App\Helpers::class
]
Then call the alias in your blade (or whatever) file.
\Helpers::instance()->productImage($product->image);
I do a lot of static functions in the Helper class so I don't need to instantiate them. Eg \Helpers::productImage($product->image)
. But the above works just as well too.
Note caps on the class:)
HTH
If you want to use the function "as is" (from the global namespace), you need to add the helpers.php file path to the autoload.files
part of your composer.json file, like this:
"autoload": {
"psr-4": {
...
}
"files": [
"app/helpers.php"
]
}
Then you should execute the dump-autoload
command from your terminal to update the autoloader:
composer dump-autoload
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.