Laravel Indirect modification of overloaded property error when saving to database - php

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();

Related

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.

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);

laravel passport return data with eloquent

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!');

inserting only in two columns of database using cakephp

I have about 30 40 columns but only inserting in 2 columns to practice.
Right now this is how i am inserting into database.
UsersTable.php
public function createUser($data)
{
$usersTable = TableRegistry::get('users');
$user = $usersTable->newEntity();
$user->first_name = $data['first_name'];
$user->first_name = $data['first_name'];
$usersTable->save($user);
}
and in the controller UsersController.php
function signUp()
{
if($this->request->is('post')){
$data['first_name']='test first name';
$data['last_name']='test last name';
$this->Users->createUser($data);
}
else{
$this->viewBuilder()->Setlayout('signup');
}
}
This is going fine but i have a doubt that is this a good way to do this?.
What if i have to insert 15 columns so i have to mention every entity in the model like this ?
$user->first_name = $data['first_name'];
$user->first_name = $data['first_name'];
There is a method used to patch the data into the entity so you don't have to do it by yourself: patchEntity()
patchEntity check for the passed array and assign the values to the correpsonding keys of the entity.
So instead of doing
$user = $usersTable->newEntity();
$user->first_name = $data['first_name'];
$user->first_name = $data['first_name'];
$usersTable->save($user);
you can simply do
$user = $usersTable->newEntity();
$usersTable->patchEntity($user, $data);
$usersTable->save($user);
as explained here
Even simplier you can do
$user = $usersTable->newEntity($data);
$usersTable->save($user);
usually $data comes from the request query son you don't even have to create the array yourself
in the controller:
$user = $usersTable->newEntity($this->request->data());

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

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

Categories