Laravel User - Role many to many relationship - laravel

I have created a Role table which has a many to many relationship with the User table. Models and everything in place plus i can seed all tables correct to create a default user + 3 roles.
I want to modify the scaffolded register controller so i can attach a role along with the other attributes (name, mail etc). The default create method looks something like this:
protected function create(array $data)
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
how do i call Role model ? and how do i pass it in the create function and ultimately to the view ?
My initial thought was:
use App\Role;
at the beginning of the file and
$roles = Role::all();
maybe on the create function ? that is probably wrong but i cannot think something else.
Plus how do i call it after on the view ? Role table has 3 predefined roles as i mentioned above.

You need to create user first, then you need to attach roles and return user instance. This should work for you:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$roles = [2, 4];
$user->roles()->attach($roles);
return $user;
}

Related

How to insert data from one form in different database table in Laravel

I am new to Laravel. I want to register the account so I have one form that has the details about the username, email, password, company name, and other company details. I got 2 tables in my database. Table 1 is the user table which is used to store the user details to log in like userID, email, password, and companyID (from table 2). Table 2 is the company table that stores company details. Table 2 has companyID, companyName, and so on. I want to ask how can I use one form to save my data in two different tables.
Here is the code from RegisterController
protected function create(array $data)
{
return User::create([
'username' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
First You Need To Insert In Company Table Then User Table Like This .
protected function create(array $data)
{
$company=Company::create([
'companyName'=>$data['companyName']
]);
User::create([
'username' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'companyID'=>$company->id
]);
}
Laravel has a very elegant solution for this. First you have to set the relations between both models. As it happens, your example can now cover both directions. That's why I now assume: a user can have many companies and a company only one user.
This means that in the user model you set the relation
protected function companies() {
return $this->hasMany(Company::class);
}
And in the Company Model you set this method:
protected function user() {
return $this->belongsTo(User::class);
}
Then in your controller, service etc. you can call the following:
$user = User::create([
'username' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$company = [
'companyName' => 'fooBar',
];
$user->companies()->save($company);
Link to the doc: https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

Save extra data while User Registration

I am using Breeze template.I am working with User Registration. My store() user function is like below
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
event(new Registered($user));
return redirect(RouteServiceProvider::HOME);
}
I would like to save more data (like user Date of Birth) as User details in another table while Registering User. I would like to maintain one to one relationship with User table and User details table.
Actually I would like to attache something with this event(new Registered($user));. So that I can save data to another Table along with registration. How can I do that ?
Where can I get the code of this new Registered($user) ?
create a new instance
and save all other fields with id to another table
$model2 new model2();
$model->col = $request->1;
$model->fk= $user->id;
$model->save();

Laravel 5 not generating api token on register

I have added a column for api_token and in my register controller , while creating the user I am trying to generate a unique id , but its not generating any code . Here is my create user function in register controller
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'api_token' => md5($data['email'].$data['name']),
'password' => bcrypt($data['password']),
]);
}
Do I need to add this somewhere else?
As cbaconnier mentioned, you also need to add api_token to your $fillable array in the User model.

Laravel - How should I create two separate register pages?

What would be the best approach for me to create two registration pages in Laravel 5.2? One should assign the user's role to 'buyer' and the other one to 'seller'.
Thanks in advance!
Just create two views and pass some variable in registration form, like:
{!! Form::hidden('role', 'user') !!}
And then change create() method in RegisterController (if you're using 5.3) or AuthController (for 5.2) to something like this:
protected function create(array $data)
{
return User::create([
'role' => $data['role'], // This will set role from hidden form element
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
Don't forget to add role to $fillable array in User model.

How do I modify my Laravel 5.2 registration to assign new users a role in Laravel 5.3?

I'm new to Laravel, and have been trying to build a user-role authentication system. As 5,3 is very new, there are not many resources that are beginner-friendly. I am using the authentication system created by php artisan make:auth, however I am unsure on how to associate my newly created users with a my roles table.
Initially I had been following this video series on YouTube, but the Authentication controllers differ greatly between 5.2/5.3
I'm hoping that someone can help me figure out what must be done to add in an equivalent what is done in the video to the new controller.
Laravel 5.2 Role Association
public function postSignUp(Request $request)
{
$user = new User();
. . .
$user->save();
$user->roles()->attach(Role::where('name', 'User')->first();
}
From Laravel 5.3 RegisterController.php
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
Thanks for reading.
You can modify the auto-generated Controllers:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->roles()->attach(Role::where('name', 'User')->first());
return $user;
}
To attach a role to a user by inserting a record in the intermediate table that joins the models right after creating an account, use the attach method before returning the new User, like this:
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
//attach default user role to user
$user->roles()->attach(Role::where('name', 'User')->first());
return $user;
}

Resources