Laravel create multiple user tables - php

I have two tables - users and user_attributes.
During registration user I would like to not only enter the user in the user table but also create his attributes.
AuthController
protected function create(array $data)
{
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return UserAttribute::create([
'user_id' => $data['id'], // Undefined index: id
'lvl' => 0,
'exp' => 0,
'currency' => 500,
'premium_currency' => 5,
]);
}
How do I get user_id?
PS: I'm sorry for my english.

Do this
$user =new User;
$user->thing1 = 12;
$user->thing2 =32;
$user->save();
And now as soon as you have called the save method you can get the id by doing
$user->id;
Remember! It will only work after you have called the save method.
Also remember to replace my data with your data.
For further info and explanation see here: https://laravel.com/docs/5.2/eloquent#basic-inserts
Best of luck!

Related

LaravelTrust and LaravelAuthUI can't import role to database

I have a problem with LaraTrust $User->attachRole('user'), and Laravel Auth UI. I want to attach a role upon registering a new User. After the registering, I don't see any data in the roles table.
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phonenumber' => $data['phonenumber'],
'password' => Hash::make($data['password']),
]);
$User->attachRole('user');
}
You are directly returning the created user before attaching the role.
Either:
$user = User::create([]);
$user->attachRole('user');
return $user;
Or
return User::create([])->attachRole('user');

Assigning user role upon registration in laravel issue

In my laravel application i'm trying to assign user role upon the registration. Following is my RegistrationController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'mobile'=>$data['mobile'],
'username'=>$data['username'],
'password' => Hash::make($data['password']),
'propic'=>'user-pic.png',
'user_roles' =>'customer',
]);
$lastdata = DB::table('users')->orderBy('id', 'desc')->first();
$last_id=$lastdata->id;
$user= User::where('id','=',$last_id)->firstOrFail();
$user->assignRole('customer');
}
But when I run the code user get created, activation mail has been sent but the role is not assigning! how can i fix that and where am I doing wrong?
There are a few things you might want to consider.
1) your function won't proceed further after the return statement. You are creating a user with a return statement hence your code below of that won't execute. I'll recommend storing the return object into some variable.
// let's say
$user = User::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'mobile'=>$data['mobile'],
'username'=>$data['username'],
'password' => Hash::make($data['password']),
'propic'=>'user-pic.png',
'user_roles' =>'customer',
]);
// then you can simply get it's value by
$user_id = $user->id; // you won't need to query last added row's value.
2) If the user role is not getting saved into your database then check if you have assigned that 'user_roles' field as fillable into User model.

Creation of multiple instance of an object

I am currently learning laravel and stuck with an assignment. I have the program where User will have multiple Whiteboards where he can post his notes. What i want to achieve is when User is created it should create 4 different Whiteboards.
This is working for 1 Whiteboard creation but not sure how I can achieve 4 while creating user. I have relationship set up where each user can have multiple Whiteboards and each Whiteboard will have only one User.
protected function create(array $data)
{
$whiteboard = Whiteboard::create([
'username' => $data['username'],
'name' => $data['name'],
]);
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'whiteboard_id' => $whiteboard->id,
]);
}
I expect something like this (Just dummy example) -
User A should have whiteboards created with ID 1,2,3,4
User B should have whiteboards created with ID 5,6,7,8
You can do somethings like this,
protected function create(array $data)
{
$user = User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
for($i=0; $i<=3; $i++)
{
$whiteboard = Whiteboard::create([
'username' => $data['username'],
'name' => $data['name'],
'user_id' => $user->id
]);
}
return $user;
}
In that case you have to change your relationship User (one) Whiteboard (many)

Laravel addOrUpdate() on basis of related table values?

Below is something I am trying to do:
I have users table and user_profiles table and I am inserting name, email in users table and phone, address, .... etc in user_profiles table.
I have to match each value to prevent duplication of user, I have found this laravel method addOrUpdate() but it works only for one table. But I have to match user_profiles values too i.e phone,address.
Below is example code
$result = $customer->updateOrCreate([
'name' => $request->name,
'city_id' => $request->city_id,
'area_id' => $request->area_id,
'email' => $request->email
], [
'name' => $request->name,
'city_id' => $request->city_id,
'area_id' => $request->area_id,
'email' => $request->email
]);
There any way to achieve this using Laravel techniques?
Regards
First make a relationship with user and user_profiles model like-
public function userProfile()
{
return $this->hasOne('App\Model\UserProfile','user_id','id');
}
And then in your post controller as you want to match each value to prevent duplication of user-
$result = User::where('name',$request->name)->where('email',$request->email)
->whereHas('userProfile', function($q) use ($request){
$q->where('city_id'$request->city_id)->where('area_id',$request->area_id)
)->first();
if(!$result){
////your registration here
}
If you want to check if a user with exactly the same data exists, you can't use updateOrCreate(). Do this instead:
$user = User::where('name', $request->name)->where('email', $request->email)->first();
$profile = $user->profile()->where('phone', $request->phone)->where('address', $request->address)->count();
if ($user && $profile) {
// User exists.
}
I would recommend using Laravel's Validator Facade. https://laravel.com/docs/5.4/validation#manually-creating-validators
This would check to make sure the name and email fields of the users and users_profile table are unique.
$validator = Validator::make($request->all(), [
'name' => 'required|unique:users|unique:users_profile',
'email' => 'required|unique:users|unique:users_profile',
]);
You could use updateOrCreate for both of your models for sake of uniqueness i assume email should be unique so first updateOrCreate() method will check if user exists for parameter $request->email then update if not then create and return user model instance (in both update/create case)
Second updateOrCreate() on UserProfile will check if there exist any data for user_id then update else add new row, I assume user_id will be a foreign key in user profile table
$user = User::updateOrCreate([
'email' => $request->email
], [
'name' => $request->name,
'email' => $request->email
]);
UserProfile::updateOrCreate([
'user_id' => $user->id
], [
'user_id' => $user->id,
'city_id' => $request->city_id,
'area_id' => $request->area_id
]);

Laravel: Get the ID of User::create and insert new row using that ID

I have AuthController in Laravel and I have 2 tables, one is Users and one is Users_Information and I want to insert into Users_Information upon registration.
So I want to get the id from the following method and insert a new row and set the column ID of that row to the ID of the user I have just created.
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
]);
}
I want to insert into Users_Information with a column id, current_food and current_level
I have a controller for the Users_Information called UserInformation, would I just call UserInformation::create but how would I get the id from the User::create?
Try to use ->id of returned object, something like:
$id = $this->create($data)->id;
The create() method returns the model.
$user = User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
]);
$userInfo = UserInformation::create([
'user_id' => $user->id,
'current_food' => $food,
'current_level' => $level,
]);
Suppose, I have a model name Employee and I want to insert some data in this model also want to get table id. So I can achieve this easily by below code:
$employee = new Employee();
$employee->employeeName = 'Something';
$employee->save();
$employee->id;
Eloquent has a nice way to handle saving relationships, which can be used in your case. It allows you to save a related model without accessing the model directly. Of course you must make sure your relationship is defined in the appropriate models first.
Below will create the user and their information. I assumed the method of your relationship was called information but you can adjust as needed.
$user = User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
])->information()->create([
'current_food' => $current_food,
'current_level' => $current_level
]);
Notice that we did not explicitly set user_id because we simply created the information by accessing the relationship you have defined; Laravel/Eloquent handles that for you!
use insertGetId(); it gives you the id of an inserted row.
$userId = User::insertGetId([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
https://laravel.com/docs/5.7/queries#inserts
Also, if you are not using Eloquent, you can use insertGetId:
$id = DB::table('users')->insertGetId(
[ 'name' => 'John Doe', 'email' => 'john#example.com']
);
Remember that if you set your table with an custom ID, you must indicate so in the code. In my case, my table "Antecedentes" has the custom id "ant_id" so "id" did not work and had to put "ant_id" like this:
$success = Antecedentes::create($data)->ant_id;
And i could go on.

Categories