I am working in laravel and i am using the spatie permission package
and I want to assign the different role for the user while registration I am using the radio button to get the role from a user such as editor ,writer,blogger
how to I assign the different role to user based on the user input
In Laravel Auth\RegisterController you can modify the create() function.
This is valid if you are using Spatie package.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->assignRole('customer'); //assign role to user
return $user;
}
Take that user input and use assignRole function as described in the package readme file
Something like
public function someController(Request $request)
{
....
$user->assignRole($request->input('role'));
...
}
assuming you have a form input (checkbox, radio, text) with name role
I have finally found a way to attach the different role to the user based on the user selection
In my register create function
$role = $data['userType'];
if ($role == 'User') {
$user->assignRole('User');
}elseif ($role =='Vendor') {
$user->assignRole('Vendor');
}
You can try the following code:
protected function create(array $data)
{
$user=User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'user_name' => $data['user_name'],
'role_name' => $data['role_name'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role_a = $data['role_name'];
if($role_a == 'student') {
$role = Roles::select('id')->where('admin_name', 'student')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'clg_admin'){
$role=Roles::select('id')->where('admin_name','clg_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'univ_admin'){
$role=Roles::select('id')->where('admin_name','univ_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'gov_admin'){
$role=Roles::select('id')->where('admin_name','gov_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'hod'){
$role=Roles::select('id')->where('admin_name','hod')->first();
$user->roles()->attach($role);
return $user;
}
}
Related
When I register a new user and I want to sign him in by using auth attempt it doesn't work while the user is saved to database
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::attempt($user,true);
Auth::attempt($user->only(['email','password']));
return result::repsonse(true);
} else
return self::$validate;
}
You can use Auth::login() method
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::login($user);
return result::repsonse(true);
} else
return self::$validate;
}
I am working on a Web Application using Laravel-5.8 as the backend. I am combining two classes: User and Role
ApiController.php
public function store(Request $request)
{
if(!Auth::user()->hasPermissionTo('Add Users'))
return response()->json([ "message" => 'User do not have permission'], 401);
$request->validate([
'name' => 'required|string|min:2',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed|min:6'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'activation_token' => str_random(60),
'address' => $request->email,
'about' => $request->email,
]);
if($request->role)
foreach($request->role as $role)
$user->assignRole($role);
else {
return response()->json([
'error' => 'Role Not Found!'
], 401);
}
$user->school_id = Auth::user()->school_id;
if($request->address)
$user->address = $request->address;
if($request->about)
$user->about = $request->about;
$user->save();
$avatar = Avatar::create(strtoupper($user->name))->getImageObject()->encode('png');
Storage::put('avatars/'.$user->id.'/avatar.png', (string) $avatar);
$user->notify(new SignupActivate($user));
return response()->json([
'message' => 'Successfully Added New User!'
], 201);
}
From the code above, I don't want to display all the Roles. I want to use the foreach statement to only select and display these two Roles: Admin, Staff.
That is, where role_name = Admin, Staff.
foreach($request->role as $role)
$user->assignRole($role);
How do I achieve this?
I think you can go about that in this way.
You can use the Laravel filter method which is in the documentation here Laravel Collection filter Method
This method returns an array of items that have passed a given condition
You convert your roles request into a collection first
Then use a condition like
return if($role == 'Admin' || $role == 'Staff')
Where you see return $value > 2;
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
When I register a member at Laravel, I send a confirmation email. But when I click on the verification link, the column in the database does not fill.
Sample codes:
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
]);
$user->sendEmailVerificationNotification();
return $user;
}
public function register(Request $request) {
$validation = $this->validator($request->all());
if($request->input('type') == "customer" || $request->input('type') == "company") {
if ($validation->fails()) {
return response()->json([$validation->errors()->toArray()], 400);
}else {
$this->create($request->all());
}
}else {
return response()->json([
0 => ['Üyelik sırasında bir hata oluştu. Lütfen tekrar deneyiniz.']
], 404);
}
}
1) Have you migrated the tables after running the auth boilerplate?
2) Have you checked your logs for any additional errors that might be showing?
I'm having some trouble registering new users in Laravel. In my project users are registered by system admins only. The expected behavior is that after sending the form, the new user will be stored and the admin redirected back to the register page.
However, when the form is filled and sent, 1) the new user is not stored and 2) the admin gets redirected to the homepage.
From what I could gather, I can't use Laravel's RegisterController because it was meant for users to register themselves using the default register form.
How can I customize the registration of new users so admins can do it?
My redirectTo() method on LoginController:
protected function redirectTo()
{
if (auth()->user()->role == 'admin') {
$this->redirectTo = '/admin';
return $this->redirectTo;
}
elseif (auth()->user()->role == 'professor') {
$this->redirectTo = '/professor';
return $this->redirectTo;
}
elseif (auth()->user()->role == 'student') {
$this->redirectTo = '/student';
return $this->redirectTo;
}
else {
return '/';
}
}
In RegisterController I simply added the role field:
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'role' => 'required|in:admin,professor,aluno',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role' => $data['role'],
]);
}
However, using the default RegisterController like this doesn't work and the result in explained above.
I'm trying to add one condition to laravel standard auth. I have found a lot of forums with this question. Most of them make change in vendor folder, what I don't want to do. I also found a way of adding credentials(Request $request) function in AuthController.php, but I have no luck. It looks like this:
protected function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'),
['Type' => 1]);
}
Does anyone solve this issue or can advice me what to do? Thanks
Below is the function your can use in AuthController to override the login function:
public function login(Request $request)
{
$validator = Validator::make(
$request->all(),
array(
'user_name' => 'required',
'password' => 'required',
),
array(
)
);
if($validator->fails()){
return redirect()->back()->withInput()->withErrors($validator->errors(),'invalid_credentials');
}
if (!\Auth::validate(['user_name' => $request->user_name, 'password' => $request->password])) {
return redirect()->back()->withInput($request->only('user_name'))->withErrors([
'user_name' => 'Incorrect Username or Password',
],'invalid_credentials');
}
$credentials = array('user_name' => $request->user_name, 'password' => $request->password);
if (\Auth::attempt($credentials, true)){
/* Check your user type condition */
if(\Auth::User()->type == '1'){
return redirect()->intended($this->redirectPath());
}
else{
\Auth::logout();
return redirect()->back()->withInput($request->only('user_name'))->withErrors([
'user_name' => 'Your type validation message',
],'invalid_credentials');
}
}
return redirect()->back()->withInput($request->only('user_name'))->withErrors([
'user_name' => 'Incorrect email address or password',
],'invalid_credentials');
}
Hope this helps you.. :)