在 null LARAVEL 8 上调用成员函数 tournaments()

Call to a member function tournaments() on null LARAVEL 8

嗨,在我的控制器中,我在锦标赛上有下划线(),我不知道为什么,因为我在我的锦标赛模型中定义了可填充并连接用户和锦标赛,belongsTo 和 hasMany。

你看到我的错误了吗?

感谢四位的指点。

Controller.php

    public function store(Request $request)
{

    $tournament = Auth::user()->tournaments()->create($request->all());
    $route = 'http://localhost:8000/turnaj/' . $tournament->slug;
    return redirect()->route($route);
}

Tournament.php

    protected $table = "tournaments";

public function user()
{
    return $this->belongsTo(User::class);
}

protected $fillable = [
    'title',
    'city',
    'street',
    'game_room',
    'e-mail',
    'phone',
    'text',
    'registration_link',
    'time_registration_at',
    'date_registration_at',
    'time_starter_at',
    'date_starter_at',
    'slug',
    'region_id',
    'user_id',
];

User.php

protected $table = "users";

public function tournaments()
{
    return $this->hasMany(Tournament::class);
}

由于存储操作需要登录用户,因此您应该使用auth中间件保护存储路由,例如:

Route::post('/tournaments', function () {
    // Only authenticated users may access this route...
})->middleware('auth');

现在您保证 Auth::user() 将获得当前登录的用户