我使用 laravel 11,带有 breeze 入门套件和 Livewire(volt 类 api)和 alpine。
在名为“DashboardController”的控制器中,我尝试使用“Auth::user”来呈现包含用户任务的视图,但它无法识别“user”,我之前已经做过几次了,但从未遇到过此错误。最奇怪的是,在 blade 文件中它确实识别了 Auth::user,所以目前我不知道还能做什么,我还没有发现有其他人遇到此问题。
仪表板控制器
<?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'));
}
}
仪表板.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>
用户表
<?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();
});
用户模式
<?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(route::get 是我想要实现的)
<?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';
请帮助我,我只是一名实习生