Yii Framework $model->save() work for one model only - php

I try to take the facebook information of a user in my databade. I'm in the UserIdentity to control the athentification of the user and i created this method.
<?php
public function insertFbUser()
{
$user = new User();
$user->fbId = $this->username['id'];
$user->username = $this->username['username'];
$user->email = $this->username['email'];
$user->password = $this->password;
$profile = new Profile();
$profile->first_name = $this->username['first_name'];
$profile->last_name = $this->username['last_name'];
$profile->birthday = strtotime($this->username['birthday']);
$profile->sex = $this->username['gender'];
$profile->fb_updated_time = strtotime($this->username['updated_time']);
$profile->fb_verified = $this->username['verified'];
$profile->fb_educationJson = json_encode($this->username['education']);
$profile->fb_workJson = json_encode($this->username['work']);
var_dump($user->save());
var_dump($profile->save());
}
the var_dump() show me this
boolean true
boolean false
Both models were created with the GII module. I try to only put one prile attribute at a time and it doesn't work too...
There is my DB : http://pastebin.com/u5CNKj9M
Thank you for your help!

print_r($profile->getErrors());
(Update)To get user id after saving:
$user->save();
$user_id = $user->id

Related

not work remember_token in laravel how set remember_token and cookie?

I logged in through the Laravel authentication system and set Remember_token, After going from one link to another link (Route) The authentication system is down and I am Logout ,
code for login and set remember_token :
Auth::login($user,true);
Have used this
If you are "remembering" users, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie
if (Auth::viaRemember()) {
//
}
Ref
https://laravel.com/docs/7.x/authentication#remembering-users
Code for user registration:
$user = new user;
$user->name = $request->user;
$user->email = $request->email;
$user->password = Hash::make($request->pw);
$user->tell = $request->tell;
if($request->hometel){$user->tel_sabet = $request->hometel;}
if($request->adress){$user->adress = $request->adress;}
$user->avatar = $filepath;
if($request->codepost){$user->codepost = $request->codepost;}
$user->remember_token = $request->token;
$id = $user->id;
$ok = $user->save();
if($ok){
Auth::login($user,true);
if($request->req !=""){
return redirect('reqticher');
}else {
return redirect('/');
}

Can not retrieve the id of a foreign key [Laravel]

I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.
When the User completes the form, I put the User & demands information inside those 2 tables.
But I do not know how to have the User id to put it inside the demands table.
Here is the function inside my Controller:
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user ->numStudent= $request->NumStudent;
$user ->role_id = "3";
$user ->Lastname = $request->LastName;
$user ->FirstName= $request->FirstName;
$user ->numero_etudiant = "12345678";
$user ->email = $request->Email;
$user ->password = bcrypt('idk');
$user ->adress= $request->Adress;
$user ->phone = $request->Phone;
$user ->parcours = $request->Parcours;
$demand->status_id= "3";
//problem below
$demand->User_id= $User;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$user ->save();
$demand->save();
return redirect('/demands_list');
}
But it says "Can't use method return value in write context".
Cordially
You have to save first the instance of your user before using its properties. Your code should look like this.
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user->numStudent= $request->NumStudent;
$user->role_id = "3";
$user->Lastname = $request->LastName;
$user->FirstName= $request->FirstName;
$user->numero_etudiant = "12345678";
$user->email = $request->Email;
$user->password = bcrypt('idk');
$user->adress= $request->Adress;
$user->phone = $request->Phone;
$user->parcours = $request->Parcours;
$user->save();
$demand->status_id= "3";
//problem below
$demand->User_id= $user->id;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$demand->save();
return redirect('/demands_list');
}
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.
The short answer: use route model binding and keep your controller methods organized and single-focused.
As already answered, your User needs to be saved first. I would recommend you do this step in its own controller:
// UsersController.php
public function store(Request $request) {
$attributes = $request->validate([
// validation rules
]);
$user = User::create($attributes);
return redirect('/users/' . $user->id);
}
Now that you have a User created, you can then attach related models. Create a separate set of routes pointing to a separate controller for handling the relationship:
// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController#index');
Route::post('/user/{user}/demands', 'UserDemandsController#store');
// ^^^^^^
// used with route model binding
Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):
// UserDemandsController.php
public function store(Request $request, User $user) { // <-- ROUTE MODEL BINDING
$attributes = $request->validate([
// validation rules
]);
$user->demands()->create($attributes);
}
The result is very clean, simple code.

How to update in one to one relation in laravel?

In my user model, I have the following code
public function profile()
{
return $this->hasOne(UserProfile::class);
}
In profile model,
public function user()
{
return $this->belongsTo(User::class);
}
The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.
$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';
$user = User::find($userId);
$res = $user->profile()->save($profile);
What is the correct method to update in One to One Relationship ?
I fixed it using push method. Here is the code.
$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();
You're doing right, however i could suggest a little improvement
You may use the following
$user = User::with('profile')->findOrFail($userId);
if ($user->profile === null)
{
$profile = new UserProfile(['attr' => 'value', ....]);
$user->profile()->save($profile);
}
else
{
$user->profile()->update(['attr' => 'value', ....]);
}
you are using save method to save new record. use update query
//controller
$userObj=new User();
if(!empty($userId) && $userId!=null){
$userObj->updateByUserId($userId,[
'dob' = '1999-03-20';
'bio' = 'A professional programmer.';
'facebook' = 'http://facebook.com/test/1';
'github' = 'http://github.com/test/1';
'twitter' = 'http://twitter.com/test/1';
]);
}
//model
function updateByUserId($userId,$updateArray){
return $this->where('user_id',$userId)->update($updateArray);
}

Laravel Indirect modification of overloaded property error when saving to database

I'm trying to save my eloquent model with its relationship.
According to documentation, this is how you save it.
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
This is my initial code:
$user = new User;
$user->name = request()->name;
$user->username = request()->username;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->profile->account_number = request()->account_number;
$user->push();
and it throws me the "Indirect modification of overloaded property" error.
My fix is:
$user = new User;
$user->name = request()->name;
$user->username = request()->username;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->save();
$profile = new Profile;
$profile->user_id = $user->id;
$profile->account_number = request()->account_number;
$profile->save();
What is missing in my first code for it to work? I really think it will work like that with the push() method.
In the first example, the profile does not exist yet. You are trying to modify a property of null.
$user->profile
// null
$user->profile->account_number
// Indirect modification of overloaded property
However, you can use the relationship like this after the user is saved.
// ...
$user->save();
$user->profile()->save(new Profile([
'account_number' => request()->account_number
]));
And once both models exist, you can use the relationship like this.
$user->profile->account_number = request()->account_number;
$user->push();

Grabbing userID and field upon user creation

I currently have a function that simply creates a user record in the database
$user->name;
$user->address;
$user->save();
Once this is done, I've created an id for them in my users table.
I know I can return $user, but specifically how can I grab the id and name from that to be used in a call like so:
$user->save();
//return $user id and $user name
$update = new UpdateTable($id,$name);
When you call $user->save(), the id (or primary key if it is not id) becomes available via $user->id. So, you'd simply pass the following to your UpdateTable() method:
$user = new User();
$user->name = "Test";
$user->address = "123 Somewhere";
$user->save();
$update = new UpdateTable($user->id, $user->name);
...
Try this code
$user = User::create(['name' => 'name', 'address' => 'Some address']);
$update = new UpdateTable($user->id, $user->name);
or
$update = new UpdateTable($user->getPrimaryKey(), $user->name);

Categories