why one table is updating and the other not in laravel? - laravel

When I click the edit button, I am trying to bring data from two tables and them update them together. One is user table and other on is user detail table.
when I update the information, user table is getting updated but user_detail table is not getting updated rather creating a new row. how to solve that?
The same code is working for one table while it is not working for the other.
This is my update function.
public function update(Request $request, $id)
{
// $this->validate($request,[
// 'title'=>'required',
// 'body'=>'required',
// ]);
//$user=new User;
$user = User::find($id);
$user->student_no=$request->input('student_no');
$user->email=$request->input('email');
$user->save();
$user_detail=new Profile;
$user_detail = Profile::find($id);
$user_detail->student_no=$request->input('student_no');
$user_detail->profile_pic=$request->input('CID');
$user_detail->CID=$request->input('CID');
$user_detail->DOB=$request->input('DOB');
$user_detail->mobile_no=$request->input('mobile_no');
$user_detail->joining_year=$request->input('joining_year');
$user_detail->graduation_year=$request->input('graduation_year');
$user_detail->program_id=$request->input('programe_id');
$user_detail->work_experience=$request->input('work_experience');
$user_detail->save();
return redirect('/dashboard')->with('success','Post Updated');
The user table is getting updated but user_detail is not.

remove line,
$user_detail=new Profile;
and in line,
$user_detail = Profile::find($id);
here you can't do like this. You have to do something like this
$user_detail = Profile::where('user_id','=',$id)->first();
then your code should look like this,
public function update(Request $request, $id)
{
// $this->validate($request,[
// 'title'=>'required',
// 'body'=>'required',
// ]);
//$user=new User;
$user = User::find($id);
$user->student_no=$request->input('student_no');
$user->email=$request->input('email');
$user->save();
$user_detail = Profile::where('user_id','=',$id)->first();
$user_detail->student_no=$request->input('student_no');
$user_detail->profile_pic=$request->input('CID');
$user_detail->CID=$request->input('CID');
$user_detail->DOB=$request->input('DOB');
$user_detail->mobile_no=$request->input('mobile_no');
$user_detail->joining_year=$request->input('joining_year');
$user_detail->graduation_year=$request->input('graduation_year');
$user_detail->program_id=$request->input('programe_id');
$user_detail->work_experience=$request->input('work_experience');
$user_detail->save();
return redirect('/dashboard')->with('success','Post Updated');

Delete $user_detail=new Profile;
Use relations for update user details.
Read about $request->all() and Mass Assignment in Laravel.
Make form validation in separate files.

$user_detail = Profile::find($id);
in this line you are checking the profile data with the primary key of the profile table which might does not exist
You can try with
$user_detail = Profile::where('user_id',$id)->first();
user_id is the fk on profiles table from user id.

You should remove line $user_detail=new Profile;
and update line $user_detail = Profile::find($id); as following
$user_detail = Profile::where('user_id',$id)->first()

there two three things with your query.
$user_detail=new Profile;
$user_detail = Profile::find($id);
first of all no need for new profile line . It just made new object but you don't need that sine your going to update someone profile,
Now print your second line response weather your getting any response from it and also is it correct one because your finding id not user_id .
otherwise there is no problem with that.
hope you will find solution in this.

Related

Update record using laravel

I have a question,
I have a form (view) and after submit it saves to the db.
one of the records is id.
when I open the form again for that ID and will press submit again
what will happened it will update the record? or try to create a new record and fail since id is primary key?
so it depends on your controllers etc if you have a updateController with the correct code it can be updated but you would also need a edit method as well, If you could share your code it will be easier to say what would happen instead of guessing
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:categories',
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Save','Success');
return redirect()->route('admin.category.index');
}
If you're trying to update record based on it's id then you could do this
public function update($request)
{
$user = User::firstOrNew([
'id' => $request->id
]);
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->save();
}
It will find a record with that id, if none was found then create a new record with that id. This is just for example but you need to validate every request before update/insert.

Update the Record of Related Model in Laravel

How to update a record in the related table model by chain expression?
This is what I currently do (and it works)
$user = User::find(1);
$token = Token::where('user_id', $user->id)->first();
$token->token = $request->token;
$token->save();
But can I do the above in a more elegant way, such as?
$user = User::find(1);
$user->token()->token = $new_token;
$user->token()->save();
My User Model
public function token()
{
return $this->hasOne('App\Token');
}
In one line:
User::find(1)->token()->update(['token' => $new_token]);
Just know these things before using it:
User find could return null if the user id is not found.
The saved and updated model events will not be fired for the updated models.
The update method execution does not go through the Eloquent model methods.
However in your particular case I think it's valid, specially if you know that the user id will always be valid.
Yo can do it like this :
User::find(1)->token()->update(['token' => $new_token]);
Or do it in youApp\Token class like this :
User::find(1)->token()->update_token($new_token);
And create update_token function in App\Token class:
public function update_token(string $new_token)
{
$this->update(['token'=>$new_token]);
}
$user = User::with('token')->findOrFail(1);
$user->token->update(['token' => $request->token]);

How to update multiple table from same form?

I am trying to update two tables from the same form. i.e. updating task table and check_list table.
This is for laravel updating database. I've tried the solution from multiple questions that were asked before.
// this is my function in a controller.
public function task_update(Request $request, $id)
{
$task = tasks::findOrFail($id);
$input = $request->all();
$task->fill($input)->save();
$check_list['remarks'] = Input::get('status');
$check_list->save();
notify()->success('Task has been updated');
return redirect()->back();
}
Actually, I am passing the data with id of task to the function and want to update the table of check_list of same task_id. ?
I want to update the check_list table too, but instead it adds new row as a new data.

Laravel DB relations

I'm trying to connect users table with user_info. I've found some posts about it and it works, but I've troubles with user_info->id autoincrement.
If I set it to:
$table->increments('id');
I'm getting error that no default value is set, it works only if I add
$table->integer('id')->nullable($value = true);
Here is what I got for now:
User model
public function userinfo()
{
return $this->hasOne('App\Userinfo');
}
Userinfo model
public function user()
{
return $this->belongsTo('App\User');
}
Migration/table structure
public function up()
{
Schema::create('user_info', function (Blueprint $table) {
//There is a problem, if I don't add user_id it says that user_id doesnt exists, so I created user_id and decided to set id to autoincrement but it doesnt works so I made it like that
$table->integer('id')->nullable($value = true);
$table->foreign('id')->references('id')->on('users');
$table->integer('user_id');
$table->string('avatar',255)->default('notset.jpg')->nullable($value = true);
$table->string('looking_for',255)->nullable($value = true);
$table->string('steam_nick',40)->nullable($value = true);
$table->integer('age')->length(3)->nullable($value = true);
$table->integer('isFriendly')->length(2)->nullable($value = true);
$table->integer('isToxic')->length(2)->nullable($value = true);
$table->integer('isLeader')->length(2)->nullable($value = true);
$table->integer('isFunny')->length(2)->nullable($value = true);
$table->integer('isSkilled')->length(2)->nullable($value = true);
$table->text('description')->nullable($value = true);
$table->timestamps();
});
}
Finally UserinfoController
public function update(Request $request, $id)
{
$user = User::findOrFail($id); //Get role specified by id
$this->validate($request, [
'steam_nick'=>'max:120',
'looking_for'=>'required',
'avatar'=>'',
'description'=>'max:450',
'age'=>'min:2'
]);
$input = $request->only(['steam_nick', 'looking_for', 'description','avatar','age']); //Retreive the name, email and password fields
$userinfo = new Userinfo();
if ($userinfo->user_id == null ) {
$userinfo->steam_nick = $request->steam_nick;
$userinfo->looking_for = $request->looking_for;
$userinfo->description = $request->description;
$userinfo->avatar = $request->avatar;
$userinfo->age = $request->age;
$user->Userinfo()->save($userinfo);
} else {
$user->Userinfo()->update($input);
}
}
Phpmyadmin
img
All I need is to set id in user_info same as id in users. I don't need user_id, but couldn't make it works other way, but I'm sure it's wrong.
Okay, let's break it down piece by piece.
First, what I like to do is specifically declare what my table column is as the second argument on any hasOne and belongsTo in a model. It's not strictly necessary since Laravel does some voodoo magic to guess what the table name is - but I recommend it because it makes the relationship very clear. So, I would do this on the user model:
public function userinfo()
{
return $this->hasOne('App\Userinfo', 'user_id'); // it references user_id on your user_info table.
}
Next, let's look at your user_info migration. You were having problems with your primary key id because you were trying to set it as integer when it needs to be increments. We'll tweak the first three lines:
$table->increments('id')->unsigned();
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users'); // foreign references the user_id field in this table, since that's what's making the connection between users and users_info, we point back to the user's id
At this point, if you are able, I recommend php artisan migrate:fresh --seed. It might help with any weird database structures you have prior. This is optional, though. You can try it if it doesn't work straight away.
Now in the controller, I noticed that you were previously referencing $user->Userinfo()->update($input);, but you named the relationship userinfo() in your user model. This is probably one of the things that was giving you an issue. They must match. Try setting up your controller like so:
public function update(Request $request, $id)
{
$user = User::findOrFail($id); //Get role specified by id
$this->validate($request, [
'steam_nick'=>'max:120',
'looking_for'=>'required',
'avatar'=>'',
'description'=>'max:450',
'age'=>'min:2'
]);
$input = $request->only(['steam_nick', 'looking_for', 'description','avatar','age']); //Retreive the name, email and password fields
// Does this user have an info record? If not, create it, else update it.
if (is_null($user->userinfo)) {
// Since you already collected the data in the $input variable, we simply array_merge it with the user's id
Userinfo::create(array_merge([
'user_id' => $user->id,
], $input));
} else {
$user->userinfo()->update($input);
}
return redirect()->back();
}
So, basically what we are doing is checking to see if the user has a related record in the user_info table. If not, create it with the data. If so, simply update it. Since in our migration we declare that user_id cannot be null, we have to grab the user's id off the $user variable, and you've already grabbed all of the necessary data for the user_info table and put it in the $input variable, we simply array_merge() those two arrays when creating the user's info record.
Otherwise, if the related record already exists, we simply update the user_info record using our relationship ->userinfo().
Try that and let me know how it works.

How does associate in Laravel/Eloquent work?

I'm trying to get associate to work.
Relationship on User model:
public function group()
{
return $this->belongsTo('User');
}
So I do:
$user = new User();
//save user fields
....
$user->save();
$group = Group::find(1);
$user->group()->associate($group);
A new user is inserted, but in the FK of group_id on the user table I am getting null.
Associate needs to be before save.
$user = new User();
//save user fields
....
$group = Group::find(1);
$user->group()->associate($group);
$user->save();
Well, let say you want to associate a comment with a blog post, because the comment can only be for a specific post we will use associate.
In our Post model we will have this:
public function comments(){
return $this->hasMany('App\Comment');
}
in our comment model we have this:
public function post(){
return $this->belongsTo('App\Post');
}
In our CommentsController we will have this:
$comment = new Comment;
$post=Post::find($post_id);
$comment->post()->associate($post);
$comment->save();
Pay attention that you save it only after you associate it with the post.
you need to save user after associating
$user->save();
full code
$user = User::create([
'field1' => $request->field1,
....
]);
$group = Group::find(1);
$user->group()->associate($group);
$user->save();

Resources