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

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.

Related

Generate a unique link for each name - yii2

I am working on development of web app, Users are supposed to register on the web app.
This is my table where data is being stored post registration.
I would like to give every user a unique url which would be stored in the same table where details of the users is being saved so that their profile url shares their society name (society_name). For example, the website domain would be www.example.com and the users' url would be www.example.com/mysociety
I would like to save the unique generated url in in the field "url"(#14) of my table.
My User Register Controller looks like this
public function actionRegister() {
$this->layout = 'society';
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
$society = new \app\models\Society();
if ($model->load(Yii::$app->request->post())) {
$password= $_POST['User']['password'];
$password_hash = Yii::$app->security->generatePasswordHash($password);
$auth_key = Yii::$app->security->generateRandomString();
$mobile=$_POST['User']['mobile'];
$society = new \app\models\Society();
$random_number=mt_rand(10000, 99999);
$society->society_name = $_POST['Society']['society_name'];
$society->contact_person = $_POST['Society']['contact_person'];
$society->address = $_POST['Society']['address'];
$society->society_id =$random_number;
$society->mobile = $mobile;
$society->status =0;
$society->save();
$session = Yii::$app->session;
return $this->redirect(['regsuccess']);
}
return $this->render('society', [
'model' => $model,
'society' => $society,
]);}
PS : English is not my native language. I am newbie to yii2 and stackoverflow, please excuse me for the mistakes.
Thanks.
I solved it.
Modified my Controller
public function actionRegister() {
$this->layout = 'society';
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
$society = new \app\models\Society();
if ($model->load(Yii::$app->request->post())) {
$password= $_POST['User']['password'];
$password_hash = Yii::$app->security->generatePasswordHash($password);
$auth_key = Yii::$app->security->generateRandomString();
$mobile=$_POST['User']['mobile'];
$society = new \app\models\Society();
$random_number=mt_rand(10000, 99999);
$vp_string = trim($_POST['Society']['society_name']);
$vp_string = html_entity_decode($vp_string);
$vp_string = strip_tags($vp_string);
$vp_string = strtolower($vp_string);
$vp_string = preg_replace('[^ a-z0-9_\.]', ' ', $vp_string);
$vp_string = preg_replace('~ ~', '-', $vp_string);
$society->society_name = $_POST['Society']['society_name'];
$society->contact_person = $_POST['Society']['contact_person'];
$society->address = $_POST['Society']['address'];
$society->society_id =$random_number;
$society->mobile = $mobile;
$society->url = $vp_string;
$society->status =0;
$society->save();
$session = Yii::$app->session;
return $this->redirect(['regsuccess']);
}
return $this->render('society', [
'model' => $model,
'society' => $society,
]);}

Redirect to saving post after the send to DB LARAVEL 8

how i have to write redirect rout for redirect after save tournament to my new tournament site.
Thanks
This doesnt work
return redirect()->route('tournaments.show', $tournament->slug);
Controller
public function store(Request $request)
{
$tournament = new Tournament();
$tournament->title = $request->title;
$tournament->city = $request->city;
$tournament->street = $request->street;
$tournament->game_room = $request->game_room;
$tournament->email = $request->email;
$tournament->registration_link = $request->registration_link;
$tournament->text = $request->text;
$tournament->phone = $request->phone;
$tournament->time_registration_at = $request->time_registration_at;
$tournament->date_registration_at = $request->date_registration_at;
$tournament->time_starter_at = $request->time_starter_at;
$tournament->date_starter_at = $request->date_starter_at;
$tournament->user_id = Auth::user()->id;
$tournament->region_id = $request->region_id;
$tournament->slug = SlugService::createSlug(Tournament::class, 'slug', $request->title);
$tournament->save();
return redirect()->back();
}
This is incorrect if using resource controller,
return redirect()->route('tournaments.show', $tournament->slug);
it should be
return redirect()->route('tournaments.show', ['tournament'=>$tournament->slug]);
provided that your routeKeyName for your route model binding is set to use a slug and not an id in the model or using the new laravel route model binding in web.php
Route::resource('tournaments',TournamentController::class)->parameters([
'tournament'=>'tournaments:slug'
]);

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

Categories