How to update in one to one relation in laravel? - php

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

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

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.

How to use return redirect in laravel controller

public function getleaveType(Request $request){
$leave_types = leaveType::all();
//create leave-type
if($request->isMethod('POST')){
$leave_Type = new leaveType;
$leave_Type->leave_type = $request->input('leaveType');
$leave_Type->staff_type = $request->input('staffType');
$leave_Type->leave_days = $request->input('leaveDays');
$leave_Type->leave_description = $request->input('leaveDescription');
$leave_Type->save();
}
return redirect('leave/leaveType', ['leave_t' => $leave_types]);
}
Looks like you are passing data $leave_types to route and not to view.
It should be something like this
return view('view_name', ['leave_t' => $leave_types]);
OR
return view('view_name')->with('leave_t',$leave_types);
Edit:
Try this
public function getleaveType(Request $request){
//create leave-type
if($request->isMethod('POST')){
$leave_Type = new leaveType;
$leave_Type->leave_type = $request->input('leaveType');
$leave_Type->staff_type = $request->input('staffType');
$leave_Type->leave_days = $request->input('leaveDays');
$leave_Type->leave_description = $request->input('leaveDescription');
$leave_Type->save();
}
$leave_types = leaveType::all();
return view('view_name')->with('leave_t',$leave_types);
}
return redirect()->route('leave/leaveType')->with( ['leave_t' => $leave_types]);
Try to use redirect like above and encapsulate the values you want to pass using with function

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