最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

laravel - Auth::user() Undefined method 'user' - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked 2 days ago Luz Serrano DíazLuz Serrano Díaz 131 silver badge2 bronze badges New contributor Luz Serrano Díaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

2 Answers 2

Reset to default 4

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.

  • Authentication - Retrieving the Authenticated User
  • Container - Contextual Attributes

Import the Correct Auth Facade

In DashboardController.php file, replace this incorrect import:

use Illuminate\Container\Attributes\Auth;

with the correct one:

use Illuminate\Support\Facades\Auth;

Then your index() function should be work.

Why did this happen?

  • You mistakenly imported Illuminate\Container\Attributes\Auth, which is not the correct Auth facade.

  • Blade templates (dashboard.blade.php) recognise Auth::user()
    because Blade automatically provides access to facades.

  • However, Controller need the correct namespace
    Illuminate\Support\Facades\Auth.

发布评论

评论列表(0)

  1. 暂无评论