Search code examples
laravel-5aliaslaravel-facade

Why does my Laravel installation need prefixing \ backslash for facades aliases


I don't know the reason for malfunction of the following example:

Auth::user()->id 

However, just prefixing it with backslash makes it works fine:

\Auth::user()->id

This is a snippet from config/app.php

'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,

The server is Apache on Ubuntu 16.04


Solution

  • That's how namespaces work.

    When you're in a typical Laravel model, controller, etc., you're within its namespace - something like App or App\Http\Controllers or whatnot. As such, Auth::foo() means App\Auth::foo() or App\Http\Controllers\Auth::foo(), respectively.

    This is why the examples that teach you how to use Auth all do use Illuminate\Support\Facades\Auth; before they use the Auth class, and say things like:

    We will access Laravel's authentication services via the Auth facade, so we'll need to make sure to import the Auth facade at the top of the class.