调用未定义的方法App \ User :: events()

时间:2019-04-19 06:05:57

标签: laravel

我正在尝试将数据存储到数据库中,但是出现的错误是:

  

调用未定义的方法App \ User :: events()

public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'slug'  => 'required|unique:events',
            'body'  => 'required',
            'date'  => 'date_format:M-d-y H:i:s',
            'time'  => 'required'
        ]);

        $request->user()->events()->create($request->all());

        return redirect('/backend/blog')->with('message', 'Your event was created successfully');
    }

2 个答案:

答案 0 :(得分:1)

尝试一下:

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required',
        'slug'  => 'required|unique:events',
        'body'  => 'required',
        'date'  => 'date_format:M-d-y H:i:s',
        'time'  => 'required'
    ]);

    $user = User::create($request->all()); // create the user
    event(new UserRegistered($user)); // Add your own event class name.

    return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}

注意:假设您已创建UserRegistered事件。并通过event帮助方法进行调用。

答案 1 :(得分:0)

您的events()模型中似乎没有任何User关系。
假设您拥有Event模型,则可以像在User模型中那样编写:

public function events()
{
  return $this->hasMany(Event::class);
}