Laravel Classroom image

Prashant  Nigam / Student / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2 | 3 | 4 | 5 | 6|Last
Lessons:-Eloquent ORM

11.4 Pivot Tables
What if we want access to our pivot table directly, rather than just the tables that are related?
Eloquent provides the pivot() method to accomplish this task.
1 <?php
2
3 $pivot = $user->hats()->pivot();
Now we have an array of result objects, just like any other query, but for those which relate the
users hats.
What if we want to retrieve the exact row that has been used to relate an object? This is easy
with the pivot dynamic attribute. The official docs has a great example of this, and I am going
to steal it because I am a nasty person. Don’t worry, I will make it look a bit different. Kinda
like with your high school assignments?
1 <?php
2
3 $user = User::find(1);
4
5 foreach ($user->hats as $hat)
6 {
7 echo $hat->pivot->created_at;
8 }
Now we can access the created_at field on the pivot table row to see when our hat was made.
Ok, I’m getting pretty sick of hats! In fact I want to delete my hats, every last one of them.
Fortunately I know my user id, its number 7, lucky number 7. Let’s do it right now, let’s delete()
all of my hats!
1 <?php
2
3 User::find(7)->hats()->delete();
There done. I will have a cold head from now on, but its worth it now you know how to use the
delete() method.

 

 
 
 

Prashant  Nigam

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)