Aiman Nazri
Aiman Nazri

Reputation: 35

How to Store Multiple Values in Laravel 8

I have two table users and role_user. Once user registered, they will choose how many role from query using the dropdown value based on picture below.

enter image description here

When i 'dd' the data, it only brings one value from role_id even when user choose more than one role.

enter image description here

I am not sure which part that i am missing. Tried so many times but still don't get the answer. I really appreciate if someone willing to help. Here is my code

RegisterController.php

protected function validator(array $data)
{
    return Validator::make($data, [
       
        'role_id' => ['required','integer'],
    ]);
}

 public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    // $this->guard()->login($user);

    $user->attachRole($request->role_id);

    if ($response = $this->registered($request, $user)) {
        return $response;
    }

    return $request->wantsJson()
                ? new JsonResponse([], 201)
                : redirect('/dashboard');
                // : redirect($this->redirectPath());
}

protected function create(array $data)
{

    dd($data);

    return User::create([
        'role_id' => $data['role_id'],
    ]);
}

register.blade.php (dropdown specific)

 @section('plugins.Select2', true)
    <div class="form-group {{ $errors->has('role_id') ? ' has-error' : '' }}">
        {!! Form::select('role_id', $users2, 1, ['multiple' => true,'class' => 'form-control select2','placeholder'=>'Sila Pilih...']) !!}
        </select>
        @if ($errors->has('role_id'))
            <span class="help-block">
                <strong>{{ $errors->first('role_id') }}</strong>
            </span>
        @endif
    </div>

user.php (Model)

protected $fillable = [

    'role_id',
];

public function role()
{
    return $this->belongsToMany(Role::class);
}

public function setRoleAttribute($value)
{
    $this->attributes['role_id'] = json_encode($value);
}

public function getRoleAttribute($value)
{
    return $this->attributes['role_id'] = json_decode($value);
}

Upvotes: 0

Views: 4344

Answers (1)

Adnan Siddique
Adnan Siddique

Reputation: 422

I had the same requirments once. You can try this solution.

public function store(Request $request){
    $inputs = $request->all();
    if(!empty($inputs)){
        $admin = new Admin;
        $admin->name = isset($inputs['name']) ? $inputs['name'] : '';
        $admin->email = isset($inputs['email']) ? $inputs['email'] : '';
        $admin->phone = isset($inputs['phone']) ? $inputs['phone'] : '';
        $admin->role = json_encode($inputs['role']);
        $admin->password = isset($inputs['password']) ? Hash::make($inputs['password']) : '';
        if($admin->save()){
            return back();
        }
    }
}

The migration for the admin is

Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('phone');
            $table->string('email');
            $table->string('password');
            $table->json('role');
            $table->timestamps();
        });

The role is json type.

The html dropdown is multiple type with array name

 <div class="col-md-6">
                      <div class="form-group mx-1">
                        <label class="control-label mb-0 p-0 small-font" for="name">Role</label>
                        <select name="role[]" class="form-control" id="" multiple>
                          <option value="">Select</option>  
                            <option value="1">full_access</option>  
                          <option value="2">orders</option>
                        </select>
                      </div>
                    </div>

Form input here. After selecting multiple role for a user enter image description here The final output is here. enter image description here

Upvotes: 1

Related Questions