Laravel - Random password on create - laravel

I have a method that stores employee data on create however I have defined a default password to be randomly created and hashed. The password isn't stored for some reason.
Any ideas?
public function store(Request $request)
{
// get company
$company = Auth::user()->companies()->first();
// get and validate data
$storeData = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric|digits:11'
]);
// create employee with validated data
$employee = $company->employees()->create(array_merge($storeData), [
'password' => Hash::make(Str::random(40)),
]);
return redirect('/employees/' . $employee->id )
->with('success', 'Employee successfully created');
}

There's an typo in your code, try
$employee = $company->employees()->create(array_merge($storeData, [
'password' => Hash::make(Str::random(40)),
]));
The array_merge is closed too early and only contains what you have in the $storeData array.

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 store data in one table with distinct attributes in Laravel 8

Need a little help with Laravel 8, I have two users with the same attributes but the other one has another attribute :
Seeker: name, email, password
Agent: name, email, password, broker license no
This is my form:
If the user registers as an agent, other fields require only for an agent.
I'm having trouble on how to store it in a database.
protected function create(array $data)
{
$r_id = isset($data['agent']) ? 2 : 3;
return User::create([
'given_name' => $data['given_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $r_id, ]);
}
you can create another table for information agents and use relationship with column id in table users
Sample code :
$user = User::create([
'given_name' => $data['given_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $r_id
]);
if($r_id === 2){
Agent::create([
'user_id' => $user->id,
.
.
...
]);
}
User relation to Agent :
public function agent()
{
return $this->belongsTo(Agent::class, 'id', 'user_id');
}

error getting a user existing in laravel sanctum

I have a error, I'm using sanctum and I want to check that the email does not exist
the if returns an empty array but the if is satisfied because it returns true
$mail = $request->input(['email']);
if ($search = User::where('email', $mail)->get()) {
return response()->json(['msg' => 'account already exist'], 409);
} else {
$validate = $request->validate([
'name' => 'required|string|',
'email' => 'required|string',
'password' => 'required|string'
]);
}
any solution?
Why not use the Laravel validation since this looks more like validation, so something like:
$request->validate([
'name' => 'required|string|',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string'
]);
with this you don't need to do an if else. You can check the Laravel docs on https://laravel.com/docs/8.x/validation#introduction for more details

How to access the reset password mailable in the new version of laravel

I would like to use the reset password mailable for my project but I do not know how to access it in laravel 6.1
Here is my method
public function store(Request $request)
{
$validatedData = $request->validate([
'address_id' => 'required',
'name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'POBox' =>['required', 'min:6', 'max:6'],
'role_id' => 'required',
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$newuser = User::create([
'address_id' =>$request->address_id,
'name'=> $request->name,
'email' => $request->email,
'POBox'=> $request->POBox,
'password' => Hash::make($quickpass),
'role_id' => $request->role_id,
]);
Mail::to($newuser->email)
->send( );
return view('admin.index')->with('message','The user has been created and a password reset email has been sent to them.');
}
The Notification used is Illuminate\Auth\Notifications\ResetPassword. It builds a MailMessage inline.
The PasswordBroker can be used to create the token and send off the notification for you. The method sendResetLink will take an array of credentials to find the User by.
Illuminate\Auth\Passwords\PasswordBroker
$resp = Illuminate\Support\Facades\Password::broker()->sendResetLink([
'email' => '...',
]);

Find duplicates in Laravel Eloquent

The following code I have on the controller is below.
public function add(Request $request)
{
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = new ProjectResearchers();
$researcherToProject->user_id = $request->userSelected;
$researcherToProject->project_id = $request->projectSelected;
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
return new ProjectsResearchersResource($researcherToProject);
}
Should I make another validation or create a function?
Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?
You can do it using updateOrCreate method, the first array is the unique values that you are looking for, if not found it will create the entry, if it finds them it will just update the fields in the second array so do this instead:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::updateOrCreate(
['user_id' => $request->userSelected, 'project_id' => $request->projectSelected],
['created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
);
return new ProjectsResearchersResource($researcherToProject);
}
or if you don't want to update at all, you can just check if it exists before storing:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = new ProjectResearchers();
if( ! ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->exists()) {
$researcherToProject = new ProjectResearchers();
$researcherToProject->user_id = $request->userSelected;
$researcherToProject->project_id = $request->projectSelected;
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
} else {
$researcherToProject = ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->first();
}
return new ProjectsResearchersResource($researcherToProject);
}
Additionaly to #nakov answer:
firstOrCreate() can combine 2 ways and looks cleaner:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::firstOrCreate([
'user_id' => $request->userSelected,
'project_id' => $request->projectSelected
]);
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
return new ProjectsResearchersResource($researcherToProject);
}
Or if you don't want to update:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::firstOrCreate([
'user_id' => $request->userSelected,
'project_id' => $request->projectSelected
]);
if(!$researcherToProject->id){
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
}
return new ProjectsResearchersResource($researcherToProject);
}
change the following:
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
to
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required|unique:ProjectResearchers,project_id,NULL,id,user_id,'.$request->userSelected
]);
this will work check if the combination of user-project already exists inthe table called ProjectResearchers.
for more information about the unique validation rule visit the Laravel Documentation.

Resources