Thursday, 1 September 2016

Unknown

List of eloquent Relationships in laravel -Part 1

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
  1. id
  2. name
  3. email
2.posts,following are the fields-
Posts table model name- Post
  1. id
  2. body
  3. desc
  4. 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 >

  1. Run composer and type php artisan tinker
  2. $user=App\User::find(1) - it gives user record whose id is 1
  3. To get all post related to $user we write > $posts=$user->posts()->get()
Lets tinker it to get user related to post >
  1. Run composer and type php artisan tinker
  2. $post=App\Post::find(1) - it gives Post record whose id is 1
  3. To get user to whom this post belongs we write > $user=$post->user()->first()
  4. we can retrieve use by accessing Eloquent relationships as properties > $user=$post->user

In next post we will learn more about relatonships -

  1. hasMany()
  2. hasOne
  3. Many to Many

Thank you.

Unknown

About Unknown -

Freelancer,Entrepreneur,Aesthetic bodybuilder.

    Knows :
  • Laravel Framework
  • Ionic Framework + Angular JS
  • Bootstrap
  • CSS
  • Jquery

Subscribe to this Blog via Email :