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.