Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bacordioroger's avatar

Relationship Insert

Hi. I have three models. User Chat and Message They have their respective tables.

user table

id|name|email|other fields

chat table

id|user_id|receiver_id

message table

id|chat_id|message|created_at|updated_at|

user one to many relationship to chat

chat one to many relationship to message

I've managed to insert data to this nested relationship but I don't think it's good.

        $chat = new Chat;
        $message = new Message;

        $chat->receiver_id = request('receiver_id');
        $message->message = request('message');
        
        $user->chats()->save($chat);
        $chat->messages()->save($message);

Do you have any idea how can I do this the right way? Thanks

0 likes
1 reply
mshahamirian's avatar

I do it the same, but I think you need user_id on messages table to define who's the message written by.

Please or to participate in this conversation.