So this one has been getting me for the past few days,
without bringing in an outside package. How can I assign roles to a user upon creating "them".
I have a registration form, roles table, users table and a role_user table all of the current users will be hard coded with roles upon release but as a new user is being created how can i add a field to assign them this role?
I have these functions in my User model, just not sure how to implement the assignRole function
public function roles()
{
return $this->belongsToMany('Role')->withTimestamps();
}
public function hasRole($name)
{
foreach ($this->roles as $role)
{
if($role->name == $name) return true;
}
return false;
}
public function assignRole($role)
{
$this->roles()->attach($role);
}
I assume you have a form with fields like username, first name, last name, password etc and a role select box. Each role should have the id of that role as the value.
//find the role by id
$role = Role::findOrFail($request->role_id) // select name="role_id"
// $request->role_id or $request->get('role_id') is the same thing.
// create the user
$user = User::create($request->all());
// assign the role to a user based on the select box from the form.
$user->assignRole($role);
// return a view
@jbowman99 Hey there. First I have to give you an advice as of how to fix your hasRole() method. You can just replace that foreach loop with a single like of code:
public function hasRole($name)
{
return in_array($name, $this->roles);
}
Now as for your question, you can simply listen to the event of a user created in a service provider:
public function boot()
{
User::created(function($user) {
$user->assignRole($role);
});
}
If you're using the default Laravel 5.1 auth stuff, and you want to assign a default role to every new user, you could edit the
create method in App\Http\Controllers\Auth\AuthController.php
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
//create role entry here
return $user;
}
seems to be dd'ing the correct information now, when it comes to attaching this info to the user
public function store()
{
if (Auth::attempt(Input::only('username', 'password')))
{
"would i put it here" -> $user->roles()->attach($request->input('roles));
return Auth::user();
}
return 'Failed!';
}