I have table Users
class User extends Authenticatable
{
use Notifiable;
protected $guarded = ['group_c', 'group_s', 'categories'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function groups()
{
return $this->belongsToMany('App\Group');
}
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
this table have relation 'many to many' to 2 anoter tables: Group
class Group extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}
and Category
class Category extends Model
{
public function Users()
{
return $this->belongsToMany('App\User');
}
}
I take data from Post request, and put them to Users table ,but 'group' field I write into 'group_user' pivot table, in my controller:
class UserController extends Controller
{
public function create_user(CrateNewUser $request)
{
//dd(Request::all());
if (Request::input('user_type') == '1') {
$groups = Request::input('group_c');
$categories = Request::input('categories');
User::create(Request::all())->groups()->attach($groups);
} elseif (Request::input('user_type') == '2') {
$groups = Request::input('group_s');
$categories = Request::input('categories');
User::create(Request::all())->groups()->attach($groups);
}
return $this->manage_users();
}
}
but I need also write data from another Post field 'categories' to another Pivot table categories_user by one sql request, how i can do that ?
In order to link user to a set of groups/category using their IDs you need to use sync() method. It will update the pivot table so that only synced records are linked.
The following should do the trick:
$user = User::create(Request::all());
$user->groups()->sync($groups);
$user->categories()->sync($categories);