1

I've got 2 models, User, Role and a pivot table. Currently in my controller it shows in checkbox the roles that that user has, how do I do it that it stores wanted role into database? How do I write the ajax to save it to the database when I click submit(potvrdi) button? Current ajax(part) that you see here is for displaying data in table. Script for this function is written in the view

Controller

public function action(Request $request)
    {
        if ($request->ajax()) {
            $query = $request->get('query');
            if ($query != '') {
                $data = User::where('surname', 'like', '%'.$query.'%')
                    ->orWhere('name', 'like', '%'.$query.'%')
                    ->orWhere('phone', 'like', '%'.$query.'%')
                    ->orderBy('id')
                    ->get();
            } else {
                $data = User::orderBy('id')
                    ->get();
            }
            return json_encode($this->generateUserTable($data));
        }
    }

    public function generateUserTable($data)
    {
        $total_row = $data->count();
        $output = "";
        if ($total_row > 0) {
            foreach ($data as $row) {
                $roleNames = '';
                $userRoles = $row->roles()->pluck('id')->toArray();
                // var_dump($userRoles);
                $checked = '';
                foreach (Role::all() as $roles1) {
                    if (in_array($roles1->id, $userRoles)) {
                        $checked = 'checked="checked"';
                    }
                    $roleNames .= $roles1->role != null ? $roles1->role.' '.'<input type="checkbox" '.$checked.' name="role" value="'.$roles1->id.'" class="checkbox" id="checkboxId">'.' ' : '';
                }
                $output .= '
                    <tr>
                        <td>'.$row->surname.'</td>
                        <td>'.$row->name.'</td>
                        <td>'.$row->phone.'</td>
                        <td>'.$roleNames.'</td>
                        <td><button type="button" id="potvrdi" class="potvrdi-button btn btn-primary" data-id="'.$row->id.'">
                        <div class="potvrdi">Potvrdi</div>
                        </button></td>
                        <td><button type="button" id="rowId" class="remove-button btn btn-danger" data-id="'.$row->id.'">
                        <div class="close">&#120;</div>
                        </button></td>
                    </tr>
                ';
            }
        } else {
            $output = '
                <tr>
                    <td align="center" colspan="5">Nema podataka</td>
                </tr>
            ';
        }
        return array(
            'table_data'  => $output,
            'total_data'  => $total_row,
        );
    }

User

protected $fillable = [
        'name', 'surname', 'email', 'phone', 'password',
    ];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
    public function IsAdmin()
    {
        $IsAdmin = false;
        $IsAdmin = !$this->roles->filter(function ($item) {
            return $item->role == 'Admin';
        })->isEmpty();
        return $IsAdmin;
    }

Role

protected $fillable = [
        'role',
    ];

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

Routes

Route::group(['middleware' => ['web', 'auth']], function () {
    Route::get('/admin', 'PagesController@admin');
    Route::post('/adminForma', 'PagesController@adminForma')->name('adminForma');
    Route::get('/users', 'PagesController@users');
    Route::get('/settings', 'PagesController@settings');
    Route::post('/settings', 'PagesController@settings');
    Route::get('/generateUserTable', 'PagesController@generateUserTable');
    Route::post('/generateUserTable', 'PagesController@generateUserTable');
    Route::get('/live_search/action', 'PagesController@action')->name('live_search.action');
    Route::post('/live_search/action', 'PagesController@action');
    Route::get('/live_search/destroy', 'PagesController@destroy')->name('live_search.destroy');
    Route::post('/live_search/generateUserTable', 'PagesController@generateUserTable');
    Route::get('/live_search/generateUserTable', 'PagesController@generateUserTable')->name('live_search.generateUserTable');
});
  • 1
    Can we see your models and the relationship you set up? If it's set up per the docs then you can do something like: $user->roles()->attach('wahtever_role'); This is straight off the laravel docs: $user = App\User::find(1); $user->roles()->attach($roleId); – Brad Goldsmith Nov 15 '18 at 13:08
  • @bradGoldsmith is write. you can use attach method for many to many relationship. – Ali Nov 15 '18 at 13:10
  • @BradGoldsmith updated – laravelnewbie Nov 15 '18 at 13:14

1 Answers1

0

In your javascript code, when the user clicks the submit button, get all the checked roles and store their ids in an array. Then post the data:

data = {
  id: user_id,
  roles_ids: roles_ids_array
}

In your controller method, get the user and sync the relationship with the ids.

$user = User::find($request->get('user_id'));
$roles_ids= $request->get('roles_ids');
$user->sync($roles_ids);

Your issue is similar to this one: Laravel attach pivot to table with multiple values

thchp
  • 2,013
  • 1
  • 18
  • 33