2

I have gone through every solution I could find over youtube, stakoverflow and other websites. I am using Select2 to add multiple roles but I a consistently getting the same error.

<select id="role" name="role_id[]" multiple='multiple' 
        class="form-control js-example-basic-multiple">
    @foreach($roles as $role)
        <option value="{{$role->id}}">{{$role->name}}</option>
    @endforeach
</select>

DD function is showing perfect result but after that it shows error.

enter image description hereIt works perfectly untill I add [] with the name="role_id[]". form action is as under.

public function store(Request $request)
{
    $this->validate($request, [
        'name'=> 'required|string|max:225',
        'status'=> 'required',
        'role_id'=> 'required',
        'email'=> 'required|string|email|max:225|unique:users',
        'password'=> 'required|string|min:6|confirmed'
    ]);

    $password = Hash::make($request->password);
    // dd($request->all());

    $user = new User;
    $user->name = $request->name;
    $user->status = $request->status;
    $user->role_id = $request->role_id;
    $user->email = $request->email;
    $user->password = $password;
    $user->remember_token;
    $user->save();
    // $user->roles()->sync($request->roles, false);
    return back()->with('message', 'User added successfully!!');
}
If I validate for integer 'role_id'=> 'required|integer', it shows error enter image description here

Migration is as under

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->unsignedInteger('role_id')->default(1);
            $table->boolean('status')->default(0);
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

5
  • 1
    Change it to 'role_id.*'=> 'required', and role_id is collection of array you should run that with loop and then insert in users role table since user have more than one role you need to keep them in another table like user_roles Commented Nov 29, 2018 at 5:00
  • 1
    error is here $user->role_id = $request->role_id; in this line you are assigning array ($request->role_id) to single variable. So, you should first create array and then used foreach loop on $request->role_id to assign value to array Commented Nov 29, 2018 at 5:11
  • I have another error in validation as well. If I use 'role_id'=> 'required|integer', instead of 'role_id'=> 'required', I get error "The role id is not integer". Commented Nov 29, 2018 at 5:25
  • 1
    @AliAnwar whats the error?? You should include the actual error message in your question Commented Nov 29, 2018 at 5:45
  • error is "The role id is not integer" when I validate for Integer. Commented Nov 29, 2018 at 6:08

5 Answers 5

5

$request->role_id is array so you can't store array to database directly so you can use following,

  $user->role_id = json_encode($request->role_id);

Later you can use json_decode function to get array of role_id.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answering to my question. I am getting another error with this code.
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '["2","3"]' for column 'role_id' at row 1 (SQL: insert into users (name, status, role_id, email, password, updated_at, created_at) values (Admin, 0, ["2","3"], [email protected], $2y$10$DEzjq.XtHPL06FnbtPTa9Oht0Bm5k9eJQT1dh6.A/5TBmVqMGi3yy, 2018-11-29 06:22:48, 2018-11-29 06:22:48))
2

As you have pivot table for roles than you dont need role_id column in your users table

public function store(Request $request)
{
$this->validate($request, [
    'name'=> 'required|string|max:225',
    'status'=> 'required',
    'role_id'=> 'required|array',
    'email'=> 'required|string|email|max:225|unique:users',
    'password'=> 'required|string|min:6|confirmed'
]);

$password = Hash::make($request->password);
// dd($request->all());

$user = new User;
$user->name = $request->name;
$user->status = $request->status;
$user->email = $request->email;
$user->password = $password;
$user->remember_token;
$user->save();

foreach($request->input('role_id') as $role)
{
   $user->assign($role);
}
// $user->roles()->sync($request->roles, false);
return back()->with('message', 'User added successfully!!');
}

14 Comments

Thanks for replying to my question but I am getting error again with this code.
Please check this 33:00 to 33:35 in this tutorial youtube.com/watch?v=BNUYaLWdR04&t=232s
That is because you have set length in your database column role_id that is exceeding when you are selecting more than one roles in your dropdown. so make it larger as varchar(256)
use required|array to validate as an array
I am following ur suggestions.
|
2

Problem:

$request->role_id is an array. not a single data.

Suggestion:

Here two things

You allocating multiple rules with an user

You should not store your rules in users table

You should do that like this:

create another table to store users role

and store user rules separately

Example:

      $user = new User;
      $user->name = $request->name;
      $user->status = $request->status;
      $user->email = $request->email;
      $user->password = $password;
      $user->remember_token;
      $user->save();

      $roleAssigns = [];
      foreach($request->role_id as $role){
          $roleAssigns[] = [
              'role_id' => $role,
              'user_id' => $user->id
          ]
      }
      //UserRole is the model of user_roles table
      UserRole::insert($roleAssigns);

3 Comments

You have pointed out the problem rightly. I tried your code but again I am getting syntax error. I have another error in validation as well. If I use 'role_id'=> 'required|integer', instead of 'role_id'=> 'required', I get error "The role id is not integer". I have seen many people using many to many relationships adding data the same way.
if controller want integer type role_id then you should pass integer from view. its the view issue.
I am following the process as Alex is following in many to many relations in his youtube tutorial. I have also seen in many tutorials for the many to many relationships. But in my case its not working. Please check this 33:00 to 33:35 in this tutorial youtube.com/watch?v=BNUYaLWdR04&t=232s –
0

You cannot "echo" an array, that is the error.

you will need to collect the lines in an array, and then return that array

Comments

0

If you want to output an array for your .js code, you may use

@json($array)

since Laravel 5.5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.