Update by referring foreign key - laravel

Password already been exist in Passw Model/Table. Here i want to change my password.
I want to update using regist_id(foreign key), not by Id in table passw.
Controller:
$passw = Passw::whereRegist_id($id)->get(); //Regist_id is an foregin key
$regist->pass()->update([
'password1' => $request->newpassword,
'password2' => $request->newpassword1
]);
return view('welcome');
Regist Model:
public function pass(){
return $this->hasOne('App\Passw');
}
When i give update it redirect to welcome page. But not password value been changed.
Where am i do mistake.

You can update it like this
$passw = Passw::where('regist_id', $id)->first();
$passw->update([
'password1' => $request->newpassword,
'password2' => $request->newpassword1
]);
You can fetch Regist model using $id
$regist = Regist::with('pass')->find($id);
$regist->pass->update([
'password1' => $request->newpassword,
'password2' => $request->newpassword1
]);

Related

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

Insert into two tables in Laravel

I have a register form, in that form user can select whether they are Farmer or Buyer from a dropdown list. If the user select Farmer then I want to add the newly created user_id to the farmer table. If the user select Buyer then I want to add the newly created user_id to the buyer table.
But the behaviour now is when the user select Buyer from the dropdown list. The newly created user_id is saved on the farmer table instead of the buyer table.
How do I save the newly created user_id to the corresponding table?
Below are my code:
$user = User::create([
'username' => $data['username'],
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'group' => $data['group'],
]);
$farmer = Farmer::make([
'user_id' => $user->id,
]);
$user->farmer()->save($farmer);
return $user;
do like this.
$decide = $data['select_option'];
if($decide == 'farmer'){
$farmer = Farmer::create([
'user_id' => $user->id,
]);
}
elseif($decide == 'buyer'){
$buyer = Buyer::create([
'user_id' => $user->id,
]);
}
I think you have a couple issues:
First, you are not using the check you described;
there is select form that decide if user is farmer or buyer
Second, you are just creating a farmer, nothing to do with the buyer you described
if the user is buyer, then buyer table get his/her user_id
Solution, is you need to first utilize the check, then create those table entries appropriately.
Also, please wrap your code in a transaction:
DB::transaction(function(){
// Your code here...
})
Thank you guys for help me, I found the easiest way to solve my issues with this below :
if ($user->group == 2) {
$buyer = Buyer::create([
'user_id' => $user->id,
]);
}elseif ($user->group == 3) {
$farmer= Farmer::create([
'user_id' => $user->id,
]);
}
$user->save();
return $user;

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

How to associate from a parent model to another

$user = User::create(['name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password')),
'place_id' => request('place_id'),
'role_id' => request('role_id') ,
'status' => request('status')]);
if (request('role_id') === 3) {
$user->courier()->associate($user);
$user->save() ;
}
I want to insert in my couriers table the user_id of that inserted user if it has role_id of 3. I tried this but didn't work.
If you want to associate the user with a particular courier, there must be the corresponding courier. First of all, you have to find it or create a new courier. If you have id of the courier then you can try the following.
$courier = Courier::find($user->id);
$courier->user()->associate($user);
$courier->save();
The above code will update user_id field of the courier with courier_id with the id of $user

Two store() methods, one doesn't work (Call to undefined method save())

One of two similar store methods doesn't work. Could you clarify this for me?
Relations
A Team hasMany Users <> A User belongsTo a Team
A User hasMany Characters <> A Character belongsTo a User
Working Code (CharacterController)
public function store()
{
$fighters = Fighter::pluck('name')->toArray();
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|not_in:'.Rule::notIn($fighters).'unique:characters',
'fighter' => 'required|in:'.Rule::in($fighters),
]);
auth()->user()->characters()->save(new Character([
'name' => request('name'),
'fighter' => request('fighter'),
]));
return redirect()->route('character.index');
}
Not Working (TeamController)
public function store()
{
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|unique:teams',
]);
auth()->user()->team()->save(new Team([
'name' => request('name'),
'fame' => 0,
]));
return redirect()->route('team.index');
}
Questions
Why is the same method not available? Is it relation stuff?
Is the create method better? Should I try to use it?
Thought I know what I'm doing, now it turns out I don't...
Thank you for helping.
team() is a belongsTo relation, you probably have a team_id col in your user table which you want to associate with the team.
public function store()
{
$this->validate(request(), [
'name' => 'required|min:3|max:25|alpha_num|unique:teams',
]);
// create and save team
$team = new Team([
'name' => request('name'),
'fame' => 0,
]);
$team->save();
// associate current authenticated user with team (set foreign key) and save user
auth()->user()->team()->associate($team)->save();
return redirect()->route('team.index');
}

Resources