【问题标题】:How to override this function to store data in DB?如何覆盖此函数以将数据存储在数据库中?
【发布时间】:2019-09-27 04:42:07
【问题描述】:

在 BroadcastServiceProvider.php 中,当用户加入频道时,我有数据,我想将其存储到数据库中。我想知道如何覆盖这个 storeUser() 函数以使其工作(我以前使用过这个函数,但它是在其他情况下使用的)。

   public function storeUser() {
       UserInfo::create([
      'ip' => Request::ip(),
      'name' =>  Auth::user()->name    
    ]);  
  }

BroadcastServiceProvider.php

   Broadcast::channel('chat', function ($user) {
        $ip = Request::ip();
        if (auth()->check()) { 
            return [
                'id' => $user->id,
                'ip' => $ip,
                'name' => $user->name
            ];
        }
    });

【问题讨论】:

  • storeUser函数在哪里定义的?
  • @jfadich 我已经为它创建了 UsersController.php。
  • 为什么不把它移到UserInfo模型上的静态方法,然后在UsersController和广播类中调用UserInfo:: storeUser()
  • @jfadich 你能更具体一点吗?我不确定我明白你的意思。

标签: sql laravel


【解决方案1】:

更新 UserInfo 模型以具有 storeUser 方法。

class UserInfo
{
   public static function storeUser() {
        UserInfo::create([
       'ip' => Request::ip(),
       'name' =>  Auth::user()->name    
   ]);  
} 

然后你可以在广播器中调用它

Broadcast::channel('chat', function ($user) {
    $ip = Request::ip();
    if (auth()->check()) { 
        UserInfo::storeUser();
        return [
            'id' => $user->id,
            'ip' => $ip,
            'name' => $user->name
        ];
    }
});

您也可以在需要时在用户控制器中以相同的方式调用它UserInfo::storeUser();

【讨论】:

  • 您的意思是 storeUser 而不是 recordUser?
  • 我应该指定一些路线吗?因为目前,什么都没有发生。
  • 我对你的问题感到困惑。我认为它正在按您的需要工作,而您只是想添加商店用户调用。
  • 无论如何调用未定义的方法 App\UserInfo::storeUser。这一行 UserInfo::storeUser() 给出了错误。我添加了使用 App\UserInfo。也许还有其他我必须使用的东西?我只是想弄清楚它是如何工作的。
  • 您是否将方法添加到模型中?该错误表示您没有,或者您将其命名为不同的名称。
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多