Reputation: 1080
I am using Laravel. I am trying to relate user model and message model to many-many relation. When I access a users message it is saying function not defined. But the that function is defined. This is the error I am getting
Call to undefined method Illuminate\Database\Eloquent\Collection::messages()
User Model.
public function docs(){
return $this->belongsToMany('Doc');
}
public function messages(){
return $this->belongsToMany('Message');
}
Message Model.
public function users(){
return $this->belongsToMany('User');
}
I am trying to store message for selected users. This is where the error rises. I have also set the pivot table.
Messages Controller.
public function store()
{
//
$input = Input::only('title', 'body', 'sel_users');
$msg = Input::only('title', 'body');
$sel_users = Input::only('sel_users');
$this->messageForm->validate($input);
$insert = Message::create($msg);
$id = $insert['id'];
foreach ($sel_users as $userid) {
$user = User::find($userid);
$user->messages()->attach($id);
}
return Redirect::route('messages.index');
}
Upvotes: 0
Views: 56
Reputation: 81187
Your problem is that userid
in the loop is an array not single id:
foreach ($sel_users as $userid) {
$user = User::find($userid); // find() provided with array returns collection...
$user->messages()->attach($id); // .. so here you can't call messages() on that collection
}
// it works the same as:
// User::whereIn('id', $userid)->get();
This is because Input::only(...)
returns array, and you must have had an array of ids in sel_users
too, so:
$sel_users = Input::only('sel_users');
// $sel_users = array('sel_users' => array( id1, id2 ...) )
What you wanted here is this:
$sel_users = Input::get('sel_users');
// $sel_users = array( id1, id2 ...)
Then the rest of your code will work as expected.
Upvotes: 1