How to remove and update data on relations table using laravel eloquent? - laravel

I have three tables. they are,
users
id name
1 personA
2 personB
3 personC
skills
id name
1 html
2 css
3 javascript
userskills
userid skills_id
2 3
2 1
1 2
1 3
I get the data through the request like [2,1] and the user id 2. On the user skills table in userid 2 there are skills_id3,1. Now i have to remove skills_id 3 and insert skills_id 2 on the userid 2.
How can i achieve it through laravel eloquent method.

As you have a pivot table you can use belongsToMany relationship. Adding the relationship in your User Model
public function skills()
{
return $this->belongsToMany(Skill::class, 'userskills','userid', 'skills_id');
//userskills is the pivot table
}
Now to update use the sync method.
$user = User::findOrFail(2); //your request id
$user->skills()->sync([1, 2]); //request array
This will remove the 3 from the pivot table and add 2 in the table.
Read more about this relationship in here

Your question is little ambiguous but lets assume that you are getting the user id 2 and the skills you want to remove from userskills is 2,1
For deleting
UserSkills::where(['userid' => 2 ])->whereIn('skills_id',[2,1])->delete();
For inserting
UserSkills::create(['skills_id' => 2, 'userid' => 2 ]);

An easier approach using relation would be
$user->skills()->sync([2, 1]);
Sync will remove those skills which are not present in the sync method.

Related

Laravel recursive relationship return error in query

i have model Hobbies with these relationship
public function sub_hobbies(){
return $this->hasMany(Hobbies::class, 'parent_id')->with('media');
}
public function allsub(){
return $this->sub_hobbies()->with('allsub');
}
in my table hobbies i have data like this
id name parent_id
1 hobbie 1 null
2 hobbie 2 1
3 hobbie 3 2
with my query Hobbies::with('sub_hobbies')->where('parent_id', null)->get(); i get the hobbies with sub_hobbies but there is the third stage, so when using Hobbies::with('allsub')->where('parent_id', null)->get(); i except to have 3 stage of hobbies but i got error 500 without error message
i'm in laravel 8.75.0
EDIT
I found in my log that it make infinite sqlquery, i don't know why it behave like this, i use Mysql if there is something to do with it

Retrieve all records attached to multiple users in Laravel

How to retrieve all records which had been attached to multiple users, please? For example I need each and every post attached to either user A, B or C. I've belongsToMany relationship set correctly, but don't know how to merge them all together. Thank you!
Posts below are attached to each user by belongsToMany relationship.
User A - Post 1 / Post 2
User B - Post 3 / Post 4 / Post 5
User C - Post 3 / Post 5 / Post 6
Now, for User D I need an eloquent of all these Posts (Post 1,2,3,4,5,6).
Can't you just query through users ID's? Like so:
$posts = Post::whereHas('users', function($q) use($usersIds) {
$q->whereIn('id', $usersIds);
})->get();
Since posts are attached to user by belongsToMany relationship, you can simply use the relationship from Post model to fetch the data. Suppose users is the name of relationship in Post model.
$result = Post::with('users')->whereIn('id',$userIds)->get();

Laravel belongsToMany pivot with multiple columns

I currently have two tables in the DB and a pivot table to join them when I need to do a belongsToMany lookup. The basic example is one DB table is 'teams' and the other is 'members'. I can utilize the belongsToMany method on both the team and members model to pull their relationship with each other. A team can have many members, and a member can belong to many teams.
public function teams()
{
return $this->belongsToMany(Team::class);
}
public function members()
{
return $this->belongsToMany(Member::class);
}
Pivot: team_member
team_id | member_id
---------------------
1 | 1
2 | 1
3 | 2
1 | 2
How can I expand on that pivot table to include a type of member for each team? For example, member1 is a leader on team1. member1 is an assistant on team2. member1 is a generic member on team3... and so on. Can I just add a column to that same pivot table? Would it be the membertype_id? How can I relate that to another model/table?
This is pretty common, and Laravel handles it already. Add extra columns to the pivot table and expand your relationships to use withPivot():
public function teams(){
return $this->belongsToMany(Team::class)->withPivot(["teamRole", ...]);
}
Then accessing is as simple as:
$user = \App\User::with(["teams"])->first();
$team = $user->teams->first();
$teamRole = $team->pivot->teamRole;
See the Documentation for more information:
https://laravel.com/docs/5.6/eloquent-relationships
To answer the second part, which is essentially a "Triple Pivot", that requires extra functionality. See
Laravel - Pivot table for three models - how to insert related models?
for more information, and an associated Package (by the answerer on that question, not maintained, but good for an example)
https://github.com/jarektkaczyk/Eloquent-triple-pivot

How to add multiple conditions on Laravel elequent relationship

I am new to Laravel and working on 5.4 version. I have a model "A" and model "B". Model A has hasMany relationship with B. Upto here things are ok. But now, I want to add more conditions on this relationship.
By default, Laravel works only foreign key relation. I mean it matches data on the basis of only 1 condition. Here, I want more condition.
Below are the tables of both Model:
table: A
id name Year
1 ABC 2016
2 DEF 2017
table: B
id A_id name Year
1 1 tst 2016
2 2 fdf 2017
3 1 kjg 2017
By default, If I want to see records of A_id 1 from table B, then Laravel will fetch all records for A_id 1. But now, suppose, if I want to get records for 2016 then How I can I do this using Laravel relationship method?
Below are the Elequent Model for both tables:
class A extends Model{
public function b(){
return this->hasMany('B');
}
}
class B extends Model{
public function a(){
return $this->belongsTo('A');
}
}
Code to fetch records of id 1:
$data = A::with('b')->find(1)->toArray();
The above request is giving me all data from table B for id 1 but I also want to put corresponding year condition also.
Is anyone know, Ho can I do this? Please share your solutions.
Thanks
You have to constrain your eager loads, using an array as the parameter for with(), using the relationship name as the key, and a closure as the value:
$data = A::with([
'b' => function ($query) {
$query->where('year', '=', '2016');
},
])->find(1)->toArray();
The closure automatically gets injected an instance of the Query Builder, which allows you to filter your eager loaded model.
The corresponding section in the official documentation: https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads

Laravel Foreach Repeating in View

So, I have a form that has multiple text inputs. When the user posts info using these inputs it's put into my model with the user's ID, a "type ID", and the input from the user. So I'll end up with something like this in the database.
ID User_ID Type_ID Type_Details
1 1 1 yada
2 1 1 foo
3 1 1 bar
In my view I do this.
#foreach ($user->UserType as $type)
What happens is that in the view I then get the output 3 times, since it sees "type_id" for user #1. For reference, this table shown is a pivot table joining the user model and the type model. I simply added another column to retrieve the type_details information.
Ultimately, since there is only one Type_id (1), I want to only show that type once with the "yada", "foo", "bar". Not 3 times.
Thanks!
Instead of using a foreach, you can group the types using Collections:
$types = $user->UserType->implode('Type_Details', ', ')->toArray();
Then you can display in your view as:
{{ $types }}

Resources