0

我正在关注这个库进行聊天,并在其中使用存在通道

composer require beyondcode/laravel-websockets

每当我发送消息控制台时,都会在我的聊天控制台中显示此错误

Call to undefined method App\User::messages()", exception: "BadMethodCallException

我的控制器

class ChatController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('chats');
    }

    public function fetchMessages()
    {
        return Message::with('user')->get();
    }

    public function sendMessage(Request $request)
    {
        $message = auth()->user()->messages()->create([
            'message' => $request->message
        ]);

        broadcast(new MessageSent($message->load('user')))->toOthers();

        return ['status' => 'success'];
    }

用户.php

public function messages()
    {
        return $this->hasMany(Message::class);
    }

消息.php

class Message extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'messages';

    protected $fillable = ['message'];

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

为什么我的消息没有传递给其他用户

4

1 回答 1

0

更改此行

    $message = auth()->user()->messages()->create([
        'message' => $request->message
    ]);

    $user = User::find(auth()->id);
    $message = $user->messages()->create([
        'message' => $request->message
    ]);

我相信 auth()->user(); 不同于 User::class

于 2020-09-10T23:38:58.237 回答