What are laravel pivot tables and pivot tables in general? What is this all about?
Recently I made research about Pivot table. I thought I know them and What they are bu
Keep this in mind
Pivot table — is a table used for connecting relationships between two tables.
Laravel part — laravel provides many-to-many relationship where you can use pivot table
, and it is very useful for many cases.
Example:
databases: users
, post_user
, posts
User.php (Model)
class User extends Model{
public function posts(){
return $this->belongsToMany('Post');
}
}
Now, to access the all logged in user's posts: (view)
@foreach(auth()->user()->posts as $post)
- {{ $post->name }}
@endforeach
Relationship happened:
Remember we have post_user
table which is the pivot table we used. If we have:
user_id
of 1
and we expect that it is the logged in user and post_id
of 1
, 2
, 3
, 4
, all this posts will be printed out like so:
|------------|--------------|
| post_id | user_id |
|------------|--------------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
|------------|--------------|
Output: