Garet's avatar
Level 3

Why do facades work in blade templates without being declared in use?

In a Blade template I can do:

{{ Storage::url('file.jpg') }}

And it will output the storage URL of the file.

However in my controller if I do:

echo Storage::url('file.jpg')

I get "Class 'App\Http\Controllers\Admin\Storage' not found"

In order for it to work in the controller I have to:

use Illuminate\Support\Facades\Storage;

Why does Blade have access to the Storage facade without this, but the controller doesn't?

0 likes
6 replies
jlrdw's avatar

They're taken care of by Taylor in vendor folder.

Snapey's avatar
Snapey
Best Answer
Level 122

Its because in your Classes you have declared a namespace. This says that unless otherwise stated all the classes mentioned in the file are in the same namespace.

So, in the class declaring its namespace App\Http\Controllers, Log is assumed to be App\Http\Controllers\Log

As you have noted, we use \Log to alias the Log class so that it is clear its in the root namespace

So, why not for views?

The difference here is that the blade files are not inside a namespaced class. Everything is assumed to be in the root namespace, so no import is necessary

pjr's avatar

@Snapey Is it recommended to use Facades in a blade file?

gssj85's avatar

I'm having a problem where facades are Class Not Found when used inside Breeze blade views, no idea what could be causing...

Snapey's avatar

@gssj85 You can now use @use('') to import the classes that you need. Some facades are already imported (such as Str) but I don't know which they are, so its a case of trial and error.

1 like

Please or to participate in this conversation.