首页 > 解决方案 > 在 null LARAVEL 8 上调用成员函数锦标赛()

问题描述

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

你看到我的错误了吗?

感谢四位您的建议。

控制器.php

    public function store(Request $request)
{

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

锦标赛.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',
];

用户.php

protected $table = "users";

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

标签: phplaravelmodelcontrollerlaravel-blade

解决方案


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

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

现在你保证 Auth::user()会得到当前登录的用户


推荐阅读