Password with FirstOrCreate - laravel

I want to use FirstOrCreate for a new user.
Like that:
$user = User::FirstOrCreate([
'name' => $request->username,
'email' => $request->email,
'password' => User::generatePassword()
]);
generatePassword() just generate a random 8 chars string string.
Thing is is doesn't work because it's looking for a user that has this password value.
So, it works when there is no user with this email, but when there is it gives me a constraint error.
What should be the cleanest way to fix it???

You've made a grammatical error. ::firstOrCreate searches based on criteria provided, and if it's not found, it will create the database entry and return the model with that data. ::firstOrNew does that without saving the model automatically.
So, you would want this.
$user = User::firstOrNew([
'email' => $request->email,
]);
We do not include name or password because we are not checking to see if Josh with josh#stackoverflow.com using password foobar123 exists, we just want to know if josh#stackoverflow.com has an account.
Your controller logic seems a bit weird because we would first want to validate that information before creating a model, but I'll roll with it.
$user = User::firstOrNew([
'email' => $request->email,
]);
// This model does not have a DB record.
if (!$user->exists)
{
$user->name = $request->username;
$user->password = User::generatePassword();
$user->save();
}
return $user;
With that logic, we find a record based on email. If the record exists, we pass it. If it does not, we assign it a username and generate a password for it before creating the record and then pass it.

Related

Laravel create command wont insert a value in database

Hello i am new to Laravel so currently im doing a CRUD. I have created this insert function that works well except one value is never inserted. This is the code below:
public function storeClient(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'nullable',
'age'=>'required',
]);
Client::create($request->all());
dd($request->phone);
return redirect('/')->with('msg', 'Client Saved successfully!.');
}
the phone' => 'nullable', value will not insert in the database unless i update the existing values. I tried this command dd($request->phone); and it shows the correct value from the user input. Any idea why the value will be inserted as null on database?
This is the value output when i make the dd command
I tried this other code which works well but im trying to use the default create() function of laravel. This is the other code i did that works well:
public function storeClient()
{
$client = new Client();
$client->name = request('name');
$client->email = request('email');
$client->phone_number = request('phone');
$client->age = request('age');
$client->save();
return redirect('/')->with('msg','Client Saved successfully!');
}
first i did not like nullable here 'phone' => 'nullable',
then u should see what do you register in your Client table phone_number or phone,
$client->phone_number = request('phone');
i think you should rename your input name phone to phone_number and will work
When you are trying to use default create method the fields names must be same as in database.
$client->phone_number = request('phone');
this line works due to the name you entered manually.
to work with default create method change the name of field in database as phone.

Add the inserted id to the pivot table

I have a users, items, user_item tables. I need to populate the user_item table with a user_id and item_id when a user is created.
so far, I have a basic registration function
public function register(Request $request) {
$user = User::create([
'name' => $request->name,
'user_type' => $request->user_type,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$token = auth()->login($user);
return $this->respondWithToken($token);
}
So far it saves only to the users table ofcourse.
I've looked at some documentations on using attach(), however, I got stuck on this one..
In the register function, i added a $item array:
$item = Item::create([
'user_id' => !!!!, -> How do I get the id of the inserted user
'instrument_id' => $request->instrument_id
]);
$user->role()->attach($item)
Also, what is role()? is it a built-in laravel function?
Note that I haven't tried running this function since I got stuck on these problems. So I don't event know if it's gonna work.
Anyone help me on this one? I'm a laravel newbie and got really confused on the documentations.
the method create return the model it self after loading it's attributes from db,
so when you want the user id just use $user->id after create() method.
for the default permission that shipped with laravel it is
spatie/laravel-permission
and to assign role to a user you can use:
$user->assignRole('writer'); // just set role name

Laravel, Forcing A Unique Rule To Ignore A Given ID

I am following the instructions from the Laravel Documentation but I can't seem to make the rule work. Basically, I want to add a unique rule for both email and username fields for updating the user profile, but it doesn't seem to work. Am I missing something?
Here is the function for updating user credentials
public function updateCredentials(Request $request, User $user)
{
Validator::make($request->all(), [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'username' => [
'required','string','min:4','max:255',
Rule::unique('users')->ignore($user->id),
],
'email' => [
'required','string','email','max:255',
Rule::unique('users')->ignore($user->id),
],
'asdf' => 'required',
'type' => 'required',
])->validate();
}
Thanks in Advance!
If you want to update user profile,without changing his id,you dont need to set specific rule for that.
Without explicitly setting the new user id,it should stay the same.
You can just name the data you want to change like this:
$user->name = request('name');
$user->lastname = request ('lastname);
$user->email = request('email');
...
$user->save();
session()->flash('message','Profile update complete!');
return redirect('/home');
Doing this the data you want will update,but the id will stay the same.
Seems to be some bug.
Adding filed name worked for me:
Rule::unique('users')->ignore($user->id, 'users')

How to Force a Unique Rule To Ignore A Specific User in Laravel 4?

On my set-password view, I want to allow user to edit their own user name and email.
In my controller, I force my validation to ignore the validation on the user with the same activation code.
I still get the error message.I know, I am missing a step, I not sure how to fix this.
Can you give me a quick tip or point out what I missed ?
I've tried, and here is what I come up with.
Code
public function postSetPassword(){
$user = User::where('code','=', Input::get('code'))->firstOrFail();
$code = $user->code;
$validator = Validator::make(Input::all(), array(
'password' =>'required|min:6',
'password_again' =>'required|same:password',
'logo_path' =>'max:255',
'username' =>'required|unique:users,username,'. $code,
'email' =>'required|email|unique:users,email,'. $code,
... more ...
There's probably many ways to do this but one that comes to my mind is this. Just don't validate the username or email if the user hasn't changed it.
$user = User::where('code','=', Input::get('code'))->firstOrFail();
$validationRules = array(
'password' =>'required|min:6',
'password_again' =>'required|same:password',
'logo_path' =>'max:255'
);
if($user->email != Input::get('email')){
$validationRules['email'] = 'required|email|unique:users,email';
}
if($user->username != Input::get('username')){
$validationRules['username'] = 'required|unique:users,username';
}
$validator = Validator::make(Input::all(), $validationRules);

Laravel Updating a record

I'm having troubles updating a record. I have a page where users can register, this works flawlessly and has 4 fields: email, username, password and confirm password. This is a simple registration page and I dont want to turn off the visitors by presenting a lot of stuff to be filled out like full name and country, so these 2 fields can be updated on their "update profile" page. The profile page is separated into areas, the main area is a single form where only these 2 fields can be updated so no username, email, password fields here - only fullname and country.
Controller Update Profile Code
$user = User::find($id);
$user->fullname = Input::get('fullname');
$user->country = Input::get('country');
if (!$user->save())
{
return Redirect::to('edit-profile')->withInput()->withErrors($user->errors());
} else {
return Redirect::to('edit-profile')->withMessage('Profile successfully updated!');
}
My User Model rules. I'm using Ardent:
public static $rules = array(
'username' => 'required|between:3,20|unique:users|alpha_dash',
'email' => 'required|email|unique:users',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'min:5',
'fullname' => 'between:5,50',
'country' => 'between:3,50'
);
Problem here is that it returns an error message saying "Passwords do not match.". So it seems like Laravel is adding the password field in the query and also tries to validate if the passwords match. I do not want to create a separate model or a separate rules for this. How can I solve this?
To make it work when you do not display a password you can test if you are displaying it, then make it a required field, in the controller:
if ($user->exists){
$user::$rules['password'] = (Input::get('password')) ? 'required|min:5|confirmed' : '';
$user::$rules['password_confirmation'] = (Input::get('password')) ? 'required' : '';
}
$user->save();

Resources