laravel save,update data into two tables - php

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

Related

Calling a controller create() method for multiple objects from one controller

I am new to Laravel so here goes:
I am creating a page for a user to register an account for his company and enter the payment method and her own login credentials. So this one page will create a Company, a User and a Payment record. The page calls the RegisterController method in Laravel.
However, each of the three objects' create methods are defined within their own controllers. Is it valid (or even good practice) to call other controller methods from within a controller like so (some boilerplate code is missing below...I just want to get my point across)
class RegisterController extends Controller {
//boilerplate code.....
protected function create(Request $request) {
//Create the company
$objCompany = CompanyController->create($request); //gets created first since it is 'top level'
//now create the user:
$objUser = UserController->create($request,$objCompany->id); //Company ID is FK in User
//Create the paymentMethod
$objPaymentMethod = PaymentMethodController->create($request,$objCompany->id); //Company ID is FK in PaymentMethod
}//end create()
}
See rather than calling distinct controllers for table creation try to store the data directly to distinct tables from one controller itself.
like this
public function store(Request $request)
{
$data = request()->validate([
...
]);
$users = new User;
$users->name = $request->name;
$users->ltname = $request->lname;
$users->dob = $request->dob;
$users->bgroup = $request->bgroup;
$users->email = $request->email;
$users->phone = $request->phone;
$users->district = $request->district;
$users->country = $request->country;
$users->state = $request->state;
$users->city = $request->city;
$users->add = $request->add;
$users->pincode = $request->pincode;
$users->password = Hash::make(request('password'));
$users->type = 'Service Center';
$users->save();
$posts = new Post;
$posts->user_id = $users->id;
$posts->fname = $request->fname;
$posts->phone1 = $request->phone1;
$posts->email1 = $request->email1;
$posts->add2 = $request->add2;
$posts->pincode1 = $request->pincode1;
$posts->district1 = $request->district1;
$posts->city1 = $request->city1;
$posts->state1 = $request->state1;
$posts->country1 = $request->country1;
$posts->cmp_id = $request->cmp_id . $users->id;
$posts->gst = $request->gst;
$posts->badd = $request->badd;
$posts->badd2 = $request->badd2;
$posts->save();
$subscribe = new Subscription;
$subscribe->user_id = $users->id;
$subscribe->post_id = $posts->id;
$subscribe->offer_id = $request->m_option_1;
$subscribe->trial_start_date = $offers->of_start_date;
$subscribe->trial_end_date = $offers->of_end_date;
$subscribe->pck_name = $offers->pck_id;
$subscribe->valid_to = $offers->validity;
$subscribe->type = $offers->of_type;
$subscribe->save();
$transactions = new Transactions;
$transactions->user_id = $users->id;
$transactions->post_id = $posts->id;
$transactions->ddl_payment = $request->ddl_payment;
$transactions->txt_ac = $request->txt_ac;
$transactions->txt_amount = $request->txt_amount;
$transactions->txt_dat = $request->txt_dat;
$transactions->txt_ref = $request->txt_ref;
$transactions->save();
return redirect('/show');
}
Here the data which I'm accepting from the form is been stored in four tables users, post, subscription & transaction.

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

Getting Objects from database in Symfony2

I had read somewhere some day that symfony2/Doctrine2 has a method(i don't remember the method name now) that fetches all "like" objects that we specify..
For example, I have User entity that has userName , password, name, state and city as properties.. For getting all Users who has name = "vinay" and state = "karnataka", the steps goes like this,,
$user = new User();
$user->setName("vinay");
$user->setState("karnataka");
$query = $em->dontKnowTheMethod($user);
$usersList = $query->getResult();
$usersList should contain all the users whose name = "vinay" and state = "karnataka"
I searched for hours but Im not getting that method.. Im sure I had read about that method long back but I cannot recall now..
Thanks in advance..
You should start studying doctrine and symfony.
$user = new User();
$user->setName("vinay");
$user->setState("karnataka");
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$repo = $this->getDoctrine()->getRepository('YourWhateverBundle:User');
$userResult = $repo->findAll(['name' => 'vinay', 'state' => 'karnataka'])
if (!$userResult instanceof User) {
echo 'No result found';
} else {
// Do whatever you want with $userResult
}

How to get last id for relationships in a transaction between models in Codeigniter?

I have this code inside a function in user-controller. I'm, using Codeigniter.
$name_user = $this->input->post('contact-company');
$company_name = $this->input->post('name-company');
$company_orgnr = $this->input->post('orgnr-company');
$phone_company = $this->input->post('phone-company');
$email_company = $this->input->post('email-company');
//Insert a a new user
$user_info = array(
'username' => $email_company,
'name_user' => $name_user
);
$company_info = array(
'name' => $company_name,
'orgnr' => $company_orgnr,
'phone' => $phone_company,
'email' => $email_company
);
//Insert a new user in db
$query_insertuser = "START TRANSACTION";
//Get sql for inserting a new user
$um = new Usermodel();
$query_insertuser .= $um->getSQLInsert($user_info);
//Get sql for inserting a new company
$cm = new Companymodel();
$query_insertuser .= $cm->getSQLInsert($company_info);
//Get sql for inserting relation between user
//and company (How do I get ID of user and ID of company to use?)
$upm = new Userprofilemodel();
$query_insertuser .= $upm->getSQLInsert();
$query_insertuser .= "COMMIT";
//Do the atual insert
$um->insert($query_insertuser);
It's used for handling a registration through a form. (Validation is done through the form-validation libray)-
Users with username, name_user is stored in a users-table
Companies are stored in a companies-table
Relations between companies and users are stored in a
userprofile-table
I think the code is kind of self-explainatory, but I'm not clear in how to insert the relation in the userprofile-model. I do need the last inserted id for user and the last inserted id for company, but in my code I don't have that because I don't actually insert any users or companies before calling $upm->getSQLInsert();
Or am I doing this incorrectly? Please give me any pointers...
I was obviously not doing this correctly. In case anyone care to bother this is my solution:-)
User-controller (part of it)
//Insert a new user in db
$um = new Usermodel();
$um->startTransaction();
$user_id = $um->insert($user_info);
$cm = new Companymodel();
$company_id = $cm->insert($company_info);
//Insert a new user-profile for newly inserted user
$upm = new Userprofilemodel();
$userprofile_info = array(
'user_id' => $user_id,
'company_id' => $company_id
);
$upm->insert($userprofile_info);
$um->endTransaction();
User-model (part of it)
public function startTransaction() {
$this->db->trans_start();
}
public function endTransaction() {
$this->db->trans_complete();
}
public function insert(array $user_info) {
$this->db->insert('user', $user_info);
return $this->db->insert_id();
}
Company-model (part of it)
public function insert(array $company_info) {
$this->db->insert('company', $company_info);
return $this->db->insert_id();
}
Userprofile-model (part of it)
public function insert(array $userprofile_info) {
$this->db->insert('user_profile', $userprofile_info);
return $this->db->insert_id();
}

Categories