1 year ago

Saving data relationship with sync doesn't work

Posted 1 year ago by gorakhyadav

Hello everyone i am newly in laravel and i do not know to to save data with modules and permission.This is my table

module_permissions pivot table

user_id, module_id, permission_id

And this is my request data

{ "user_id": "2", "role_id": "1", "module_id": [1,2,3], "permission_id":{ "1": [1,2,5], "2": [5,7], "3": [1,2,5] } }

and this is define relation in User Model

public function userRole() { return $this->belongsToMany('App\Role','user_roles')->withTimestamps(); }

public function userRoleModule()
    return $this->belongsToMany('App\Module','user_modules')->withTimestamps();
public function userModulePermission()
    return $this->belongsToMany('App\Permission','module_permissions')->withTimestamps();

and am saving like this

$user_id = $request->user_id; $role_id = $request->role_id; $module_ids = $request->module_id; $permission_ids = $request->permission_id;

    $user = User::find($user_id);
    if (!$user)
        return response()->json(['message' => 'error'], env('NOT_FOUND'));
    $user->userRole()->sync($role_id); // This is work fine
    $user->userRoleModule()->sync($module_ids); // This is work fine
  $user->userModulePermission()->sync($permission_ids ); // But This is not work 

Please sign in or create an account to participate in this conversation.