Reputation: 6351
I am trying to attach a message to a conversation (many-to-many), but I am getting an error. What am I missing?
Pivot Table Schema
conversation_message
(conversation_id
, message_id
)
Models
class Conversation extends Eloquent
{
public function messages()
{
$this->belongsToMany('Message', 'conversation_message', 'conversation_id', 'message_id');
}
}
class Message extends Eloquent
{
public function conversations()
{
$this->belongsToMany('Conversation', 'conversation_message', 'message_id', 'conversation_id');
}
}
Controller
$conversation = Conversation::find(1);
$message = Message::find(1);
$conversation->messages()->attach($message);
Error
Call to a member function attach() on a non-object
Upvotes: 2
Views: 1479
Reputation: 81187
There are return
s missing in both methods:
class Conversation extends Eloquent
{
public function messages()
{
return $this->belongsToMany('Message', 'conversation_message', 'conversation_id', 'message_id');
}
}
class Message extends Eloquent
{
public function conversations()
{
return $this->belongsToMany('Conversation', 'conversation_message', 'message_id', 'conversation_id');
}
}
Upvotes: 5