How relationships work in laravel
Lets understand this concept using following example,there is blog where user creates many posts -
There are 2 tables - 1.users, following are the fields-
Users table model name- User
- id
- name
Posts table model name- Post
- id
- body
- desc
- user_id
Below is User Model,since user can create many posts so we implement hasMany() relationship in model
Eloquent will automatically determine the proper foreign key column on Post Model
namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { public function post() { return $this->hasMany('App\POst'); } }
Below is Post Model,since each post belongs to speccific user, we implement belongsTo() relationship.
First argument of belongsTo() is path of model , second argument is foreign_key here its user_id
namespace App; class Post { public function user() { return $this->belongsTo('App\User','user_id'); } }
Lets tinker it >
- Run composer and type php artisan tinker
- $user=App\User::find(1) - it gives user record whose id is 1
- To get all post related to $user we write > $posts=$user->posts()->get()
- Run composer and type php artisan tinker
- $post=App\Post::find(1) - it gives Post record whose id is 1
- To get user to whom this post belongs we write > $user=$post->user()->first()
- we can retrieve use by accessing Eloquent relationships as properties > $user=$post->user
In next post we will learn more about relatonships -
- hasMany()
- hasOne
- Many to Many