I have an error in my update user admin form where I want to update the profile that's corresponding to the user if he has a profile. But it throws this error:
Creating default object from empty value
I have set relationships in my model between the User and profile Profile::where('id', $user->profile_id)->first(); but when I dd it's always a null, even if there is a corresponding profile.
User.php
public function profile()
{
return $this->hasOne('App\Profile', 'user_id', 'id');
}
Profile.php
public function user()
{
return $this->belongsTo('App\User');
}
function error is in
public function update(Request $request, User $user)
{
if(\Auth::check()) {
if(\Auth::user()->type == 'admin') {
$validated = $request->validate([
'name' => 'required',
'email' => 'required|email',
'password' => 'confirmed'
]);
if(!empty($validated['password'])){
if(!$user->profile){
//Has no profile
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->update();
} else {
//Has profile
$profile = Profile::where('id', $user->profile_id)->first();
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->update();
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->update();
}
} else {
if(!$user->profile){
//Has no profile
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->update();
} else {
//Has profile
$profile = Profile::where('id', $user->profile_id)->first();
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->update();
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->update();
}
}
}
}
}
on these lines $profile = Profile::where('id', $user->profile_id)->first();
Since you are using user_id as a foreign key in the profiles table, you would expect this as your statement:
Profile::where('user_id', $user->id)->first();
Or, by using the relation:
$user->profile;
You can just use your relation and also compress the logic as :
$user->name = $validated['name'];
$user->email = $validated['email'];
if(!empty($validated['password'])){
$user->password = bcrypt($validated['password']);
$profile = $user->profile;
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->save();
}
$user->save();
Related
I am currently working on POS in laravel 8. I am having an error when I login in that "credentials do not match our records" When I login in through the default Register page than it works fine but when I register through internal panel than the data goes to the database but I face error when I log in.
Code for registration through panel:
public function store(Request $request)
{
$users = new User;
$users->name = $request->name;
$users->email = $request->email;
$users->password = Hash::make($request->name);
// $users->password = bcrypt($request->name);
$users->is_admin = $request->is_admin;
$users->save();
if($users){
return redirect()->back()->with('User Created Successfully');
}
return redirect()->back()->with('User Failed Created');
}
Default register code:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Your panel registration form is hashing the name input and not the password input.
$users->password = Hash::make($request->name);
Should probably be
$users->password = Hash::make($request->password);
#Code for registration through panel code should be like this#
public function store(Request $request){
$users = new User;
$users->name = $request->name;
$users->email = $request->email;
$users->password = Hash::make($request->password);
$users->is_admin = $request->is_admin;
$users->save();
if($users){
return redirect()->back()->with('User Created Successfully');
}
return redirect()->back()->with('User Failed Created');
}
I need to return message but I get an error.
My controller:
$user = User::findOrFail($id) ;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = $request->input('password');
$user->role_id = $request->input('role_id');
if($user->update()){
return new UserResource($user);
}
I tried:
return new UserResource($user)->with('status', 'Profile updated!');
You have to place the creation of the UserResource instance between brackets so php knows you are using the with function on this new instance.
return (new UserResource($user))->with('status', 'Profile updated!');
I am having trouble understanding and knowing how to create a one to one relationship with CRUD and file upload together, is it possible to give me a simple example on how to do it? Because when I tried to do it, for some reason my id and user_id doesn't match at all
Example, in user_info table (jack with id 1) has one userImage table(image uploaded with a user_id = 1).
This is the part that I am having trouble with in my controller:
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalExtension() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
//dd($UserImage);
return redirect('/home');
}
Sample of one to one relationship. I wish it can help you.
Example of table of Column of user table:
id
name
email
password
Example of table of Column of userimage table:
id
user_id
image_link
uploaded
User Model
public function userImage()
{
return $this->hasOne(App\UserImage::class);
}
UserImage Model
public function user()
{
return $this->hasOne(App\User::class);
}
CRUD in controller
public function store(Request $request)
{
$user = new App\User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->create([
'image_link' => $request->image,
'uploaded' => $request->date,
]);
return back();
}
public function update(Request $request, $id)
{
$user = App\User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->image_link = $request->image;
$user->userImage->uploaded = $request->date;
$user->userImage->save();
return back();
}
public function destroy($id)
{
$user = App\User::find($id)->delete();
return back();
}
Create a foreign key in your user_info table referencing userImage table.
Create unique constraint on the foreign key.
i'm doing a project where ALL user can create a post and pubblic it!
if user not logged blade enable a section with email and password to create account and post.
I would like do:
Creation user
Log user in session auth ( HERE IS MY PROBLEM, HOW CAN I DO THIS? )
Create Post (last point because i need user_id)
CONTROLLER
// if user NOT registered my form will enable email and password field --
if(!null($request->input('email') && request->input('password'))) {
// create user
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('name'));
$user->save();
// login user after create user
HOW CAN I LOG USER AFTER CREATED ACCOUNT ???
Thank you for your help!
// Get ID of user created
$get_user_id = User::where('email', '=', $request('email'))->first();
// create post
$post = new Post();
$post->title = $request->input('title');
$post->slug = str_slug($request->input('title'),'-');
$post->country = $request->input('country');
$post->zone = $request->input('zone');
$post->phone = $request->input('phone');
$post->address = $request->input('address');
$post->user_id = $get_user_id->id;
$post->save();
return redirect('/')->with('message-success', 'Post creato con successo!');
// IF USER LOGGED
}else{
$post = new Post();
$post->title = $request->input('title');
$post->slug = str_slug($request->input('title'),'-');
$post->country = $request->input('country');
$post->zone = $request->input('zone');
$post->phone = $request->input('phone');
$post->address = $request->input('address');
$post->user_id = $request->input('user_id');
$post->save();
return redirect('/')->with('message-success', 'Post creato con successo!');
}
The answer is:
Auth::login($user);
Check out the doc.
Is not so clear what you want to do here, the way you get the user id is insecure.
I'll recommend you to use $user = Auth::user(); instead to get the user id, ($user->id).
to check the login manually use
if (Auth::attempt(['email' => $email, 'password' => $password])) {}
so in your example I'll do something like:
if (!Auth::attempt(['email' => $email, 'password' => $password])) {
// create User
} else {
// $userId = Auth::user()->id;
}
// finally create post
Add a __construct() method to your class, and add following code:
public function __construct() {
$this->middleware('auth', ['except' => ['index', 'show']]);
}
And it must actually work
I set hash mutator for User model:
public function setPasswordAttribute($value)
{
\Log::info('Hash');
$this->attributes['password'] = \Hash::make($value);
}
Then I have a register function. The password hashes twice (checked in logs)
public function register(RegisterNewUser $request)
{
$user = new User();
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->password = $request->password;
$user->admin = true;
$user->save();
$this->auth->login($user);
return redirect()->route('dashboard');
}
Actually the function was originally written like this:
$user = new User($request->all());
$user->admin = true;
$user->save();
With the same result. Password gets hashed twice and I can't figure why.
I even tried:
get('test', function() {
$user = \CRM\EloquentModels\User::create([
'email' => 'zzz#zzz.zzz',
'last_name' => 'zzz',
'password' => 123
]);
});
And it gets hashed twice. No idea...