How does associate in Laravel/Eloquent work? - laravel

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

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.

Laravel MorphMany Relationship - What am I missing?

I have the defaults users table which I've altered to have userable_type and userable_id. I have various models, eg BursaryAdministrator and BursaryProvider and users can belong to either.
BA/BP Model:
public function users() {
return $this->morphMany('App\Users', 'userable');
}
Users Model:
public function userable()
{
return $this->morphTo();
}
During my migration, I've created a default BursaryAdministrator and BursaryProvider and a couple of users. I want to assign them to each:
$bp = \App\BursaryProvider::first();
$user = User::find(2);
$bp->users()->associate($user);
$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$ba->users()->associate($user);
However, they're not linking as the userable_type / userable_id fields are null. I've tried both 'associate' and 'attach'.
Whats the correct what to do this?
You could try to save() the user after association, i.e.:
$bp = \App\BursaryProvider::first();
$user = User::find(2);
$bp->users()->associate($user);
$user->save()
$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$ba->users()->associate($user);
$user->save()
Ok, so this was the correct way at the end of the day:
$bp = \App\BursaryProvider::first();
$user = User::find(2);
$user->userable()->associate($bp);
$user->save();
$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$user->userable()->associate($ba);
$user->save();
Thanks to #dparoli for pointing me in the right direction.

How to queue the logics in controller

I have used two logic in my controller in my laravel project
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
$post = MyPost::create([
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
return redirect()->to('/admin/home);
}
Is it possible to make like if user is created successfully only then the post will be created so that I can use post created by user relationship
I have tried something like if condition but it is not working
You can try the code bellow , I assume you have a user_id field in posts table since you mentio9ned a relation ship. This is not the best way but i try to keep things simple, so I just edited the code.
Note : make sure you listed all the table fields in protected $fillable in your model before using Create()
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
if($user){
$post = MyPost::create([
'user_id' => $user->id
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
}
return redirect()->to('/admin/home);
}
Enclose your query in database transaction
https://laravel.com/docs/5.8/database#database-transactions
Either you can:
DB::transaction(function() {
Model::create();
AnotherModel::create();
});
Or you can use the following to find and catch error...
DB::beginTransaction();
// Your queries here...
// Model::create();
// AnotherModel::create();
DB::commit();

why one table is updating and the other not in 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.

Laravel: Insert in pivot table [duplicate]

This question already has an answer here:
Laravel adding data to pivot table while inserting new record
(1 answer)
Closed 1 year ago.
I have 3 tables
User(id,name,email)
Role(id,rolename)
role_user(user_id,role_id)
In roles table i have following data;
id rolename
1 admin
2 user
In this scenario, I have users table is associated to roles table with many to many relation.
I have one eloquent model as
UserModel
user_roles(){
belongsToMany('Role')
}
Now I want to save data in role_user table when i create user. I have roles in dropdown.
I am using following query
$user = new User();
$user->username = $data->username;
$user->email= $data->email
$user->save();
its perfectly saves the user in user table but i want also want to save data in user_role table.
Can you guys please help me how to save this ??
Use attach() method after you create the user:
$user->roles()->attach($roleId);
In User model:
public function roles()
{
return $this->belongsToMany(Role::class);
}
In Role model:
public function users()
{
return $this->belongsToMany(User::class);
}
I assume you pass the roles as an array, then in your controller you can have something like this:
public function store(Request $request)
{
//return $request->roles;
$this->validate($request, [
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed'
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('backend.users');
}

Resources