laravelroutescontrollerlaravel-bladelaravel-11

Auth::user() Undefined method 'user'


Iḿ using laravel 11, with the breeze starter kit and Livewire (volt class api) with alpine.

In a controller named 'DashboardController' I'm trying to use 'Auth::user' to render a view with the tasks the user has but it doesnt recognize 'user', Ive done it a few times before but never have gotten this error. The weirdest thing is that in the blade file it does recognize Auth::user, so at this point I dont know what else to do, I haven't found anyone else with this problem.

DashboardController

<?php

namespace App\Http\Controllers;


use Illuminate\Container\Attributes\Auth;
use Illuminate\Foundation\Auth\User as AuthUser;


class DashboardController extends Controller
{
    public function index(){
       /*  $user = Auth::user(); */
        $user = Auth::user();
        $tasks = Auth::user()->tasks;
        return view ('dashboard', compact('tasks'));
    }
}

dashboard.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    @foreach (Auth::user()->tasks as $task)

                    <p> {{ $task->title }}</p>
                    <p> {{ $task->description }}</p>
                        
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

users table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            //add deleted_at column
            $table->softDeletes();
        });

user modal

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use HasFactory, Notifiable;
    use SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];


    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }


    public function tasks(): HasMany
    {
        return $this->hasMany(Task::class);
    }

}

web.php (the route::get is what im trying to achieve)

<?php

use App\Http\Controllers\DashboardController;
use Illuminate\Support\Facades\Route;

Route::redirect('/','/dashboard');

Route::get('/dashboard', [DashboardController::class, 'index'])
->middleware(['auth'])
->name('profile');

Route::view('profile', 'profile')
    ->middleware(['auth'])
    ->name('profile');

require __DIR__.'/auth.php';

Please help me im just an intern


Solution

  • You're importing the wrong class.

    use Illuminate\Container\Attributes\Auth;
    

    should be

    use Illuminate\Support\Facades\Auth;
    

    for Auth::user() to work.

    The reason why it works in blade is because Illuminate\Support\Facades\Auth is aliased to Auth when the Blade compiler compiles the views.


    The class you're using is a contextual attribute used to resolve a Guard.

    The way you use that one is like this. These two blocks are equivalent.

    use Illuminate\Support\Facades\Auth;
    
    // some method that will be resolved by the container, like a controller method
    public function someMethod()
    {
        $guard = Auth::guard('web');
        $user = $guard->user();
    }
    
    use Illuminate\Container\Attributes\Auth;
    
    // some method that will be resolved by the container, like a controller method
    public function someMethod(#[Auth('web')] $guard)
    {
        $user = $guard->user();
    }
    

    Alternatively you can use the Authenticated contextual attribute in your use case.

    namespace App\Http\Controllers;
    
    use App\Models\User;
    use Illuminate\Container\Attributes\Authenticated;
    use Illuminate\Contracts\View\View;
    
    class DashboardController extends Controller
    {
        public function index(#[Authenticated('web')] User $user): View
        {
            return view('dashboard', [
                'tasks' => $user->tasks,
            ]);
        }
    }
    

    Here is some documentation on the matter, just the relevant sections.