inserting only in two columns of database using cakephp - php

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

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.

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

laravel save,update data into two tables

Am having problem updating data into pivot tables.
users[id->autoincrement,username,password,firstname,lastname,lga,email]
class User extends Eloquent
{
public function lga()
{
return $this->HasMany('LGA');
}
}
userslga[id->autoincrement,user_id,lga_id]
public function user()
{
return $this->belongsTo('user');
}
public function lga()
{
return $this->belongsTo('lga');
}
lga[id->autoincrement,lg_name]
class LGA extends Eloquent
{
public function lga()
{
return $this->belongsTo('User');
}
}
When i tried querying relationship,like User::find($id)->lga i could not figure that out.but i eventually made it work using this:
$U_LGA = UserLga::where('user_id',$id)->lists('lga_id');
Now my problem is that i can store data into related tables from my controller like this:
if ($validation->passes())
{
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->type = Input::get('type');
$user->phone = Input::get('phone');
$user->password = Hash::make(Input::get('password'));
$user->save();
//save each users lga
foreach(Input::get('LGA') as $LGS)
{
$userlga = new UserLga;
$userlga->user_id = $user->id;
$userlga->lga_id = $LGS;
$userlga->save();
}
//end
return Redirect::to('/')->with('success','New user profile successfully created');
}
//return json error
return Response::json($validation->messages());
But Updating would be a problem as UserLga::find($id) would not be valid because it the same as select from userlga where id = $id,where as am suppose to be updating all teh row where the user_id is the present user id am editing and add additional lga if more lga was checked.
I need help on how to do this am confused.Or am i getting the concept wrong or is Eloquent relationship query what am suppose to do,
please someone help?
EDIT
I WOULD LIKE TO RUN THE FOLLOWING QUERIES
UserLga::where('user_id',$uid)->lists('lga_id');
I WOULD LIKE TO DO BELOW IN ABETTER WAY TO
$statement2 = "SELECT * FROM facility where LGA_id = '$fulga' ";
//loop through lga id to build query
foreach($LGA_id as $fax)
{
$statement2.= " "."OR"." "."LGA_id=". "'".$fax."'";
}
//FACILITY for User assigned LGA
$facility = DB::Select($statement2);
///////////////////////////////////////////////////////////
//generate all lgaid covered by user
///////////////////////////////////////////////////////////////////////
$ulga = UserLga::where('user_id',$uid)->lists('lga_id');
//remove the first lgaid in array to build query and avoid repetition
$sulga = array_shift($ulga);
// query
$statement = "SELECT * FROM lga where id = '$sulga' ";
//loop through lga id to build query
foreach($ulga as $lga)
{
$statement.= " "."OR"." "."id=". "'".$lga."'";
}
//user assigned lga
$LGA = DB::Select($statement);
AM SORI THIS LOOKS ROUGH A BIT BUT I WANT TO ACHIVE BETTER USING ELOQUENT RELATION QUERY

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