Laravel 5 - Get newly inserted id in transaction? - laravel

So I am running a transaction that should create a user, and fire off an event to do additional things with the new user id, including creating a settings table where the foreign key user_id in the settings table is the newly created user_id (providing the transaction works of course).
Here is what I have so far:
DB::beginTransaction();
try {
DB::table('users')->insert([
'email' => $email,
'password' => $password
]);
event(new UserWasStored($newUserId)); // How do I get the $newUserId?
}
catch(\Exception $e) {
DB::rollback();
}
DB::commit();
How can I get the $newUserId passed to the event within the transaction?

According to the documentation you should be using the insertGetId method
$newUserId= DB::table('users')->insertGetId([
'email' => $email,
'password' => $password
]);

You can also use your User model to create a new user. In return, it'll give you the user object to work with.
$user = User::create([
'email' => 'john#example.com',
'password' => bcrypt('your-password')
]);
dd($user->id);

$id = DB::table('table')->insert( $data )->lastInsertId();

Related

how to edit user email in laravel

i want to edit my user email in laravel, but when i submit the form and then it gives me an error message
The selected Email is invalid.
what do I have to do?
whats wrong with this code?
//in Create Function
'email' => 'required|email|unique:users,email',
//in Update Function is this correct?
'email' => 'required|email|exists:users,email',
Controller
This is my userController for update users
public function update(Request $request, User $user)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string|max:30',
'email' => 'required|email|exists:users,email',
'role' => 'required',
'avatar' => 'required|string|max:150'
],
[],
$this->attributes()
);
if ($validator->fails()) {
$request['role'] = Role::select('id', 'name')->find($request->role);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
}
DB::beginTransaction();
try {
$user->update([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'avatar' => parse_url($request->avatar)['path'],
]);
$user->syncRoles($request->role);
Alert::toast(
__('posts.alert.delete.message.success'),
'success'
);
return redirect()->route('users.index');
} catch (\Throwable $th) {
DB::rollBack();
Alert::toast(
__('posts.alert.delete.message.error', ['error' => $th->getMessage()]),
'errors'
);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
} finally {
DB::commit();
}
}
You still want a unique validator, so the user can't update their account to someone else's email address and cause a conflict.
However, to prevent it from failing when the user isn't updating their email address (it would fail the unique validation, because a record already exists with that email - the user's own), you'll want to exempt the user's current record from the validation.
https://laravel.com/docs/9.x/validation#rule-unique
See "Forcing A Unique Rule To Ignore A Given ID":
// at the top of your file
use Illuminate\Validation\Rule;
'email' => [
'required',
'email',
Rule::unique('users')->ignore($user->id),
]
You're validating the request requiring the email to exist in the table :
'email' => 'required|email|exists:users,email',
You need to specify unique in order to check the value is not used in the table (same as creation)
'email' => 'required|email|unique:users,email',
You can't do either
'email' => 'exists:users,email'
or
'email' => 'unique:users,email'
for update function. because if you don't change the email you have to submit the old email to the controller which is not "unique" and if you do change it then it doesn't "exist" in the database.
Instead try it like this:
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user)],
It means the email should be unique unless it is the email from current user.
See the Laravel docs for more information on this:
https://laravel.com/docs/9.x/validation#rule-unique

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();

Creation of related Models on auth RegisterController in laravel

In my application, I have tables related to users and some of these tables require a row be inserted as soon as a User is registered.
For example, I have the following models:
UserProfile,
UserAssignedRole,
UserSettings
As soon as a User successfully registers, they will need a corresponding row in the DB.
I've done the following:
protected function create(array $data)
{
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
UserProfile::create([
'user_id' => $user->id,
]);
UserAssignedRole::create([
'user_id' => $user->id,
'role_id' => 1
]);
UserSettings::create([
'user_id' => $user->id,
'nsfw' => 1
]);
return $user;
}
I'm looking for a better and more elegant way to achieve this. Is there a "Laravel" way in achieving this?
In the Larvel docs there's a chapter about Recursively Saving Models & Relationships. This is probably what you're looking for. They specify the following example:
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
You could achieve something similar by creating a user including all its relationships in one push().

how to create new user only if there is data in database-Laravel

I have done programming with other frameworks but this is new to me, thanks for your time in advanced, I'm trying to create new user on a condition that if there is data in another table then new user is created otherwise not I have put my code inside if else statement and is throwing errors.
my function for creating new user is listed below:
protected function create(array $data)
{
/*$exists = \DB::table('received_pay')->where('email', $data['email'])->first(); */
$exists=\DB::table('received_pay')->where('email', '=', $data['email'])->where('token', $data['token'])->exists();
if ($exists === null) {
// user doesn't exist
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}else{
return null;
}
}
}
this is the error it throws
You need to return User instance from the RegisterController#create method by default, you can't return null. So, do this instead of return null;:
return User::where('email', $data['email'])->first();
If it's an option to check if the user exists in the users table, you can use the firstOrCreate method:
protected function create(array $data)
{
return User::firstOrCreate(['email' => $data['email'], [
'username' => $data['username'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}
Also, you if want to check if a user exists in the received_pay table, you can leave original RegisterController#create method and add this rule to the RegisterController#validator method:
'email' => 'unique:received_pay,email',
This will not allow Laravel to create a new user if a user with the same email already exists in the received_pay table.

Resources