At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

A Guide To Laravel Eloquent Relationships – Part 1

  • By Harikrishnan R
  • August 29, 2018
  • 4258 Views

In our previous blogs, we had discussed more about Laravel and it’s features, also the future advancements and so on. But today we’re getting bit closer to Laravel and will jump into the world of Laravel Eloquent relationships. As we all aware about the Laravel eloquent relationships which is currently introduced and available from laravel 5.0 onwards. To be precise, here we will have foreign keys while creating an application and with that, each table will be connected to the other table where the Eloquent remains easy for connecting each tables. On the go, will explore each relationships and it’s fondness towards facilitating relationships around tables.

  • One to one relationships

  • One to many relationships

  • Many to many relationships

 

Why Eloquent Relationships?

Here we have 2 tables named as “students” and “marks”so to join this tables we need to apply following query,

$student = student::join(‘marks’,’marks.student_id,’=’,students.id’)->where(‘students.id’,’1’)->get();
dd($student);

 
Now you can note that the above query is too long to proceed, so when we try to connect more tables then it would be too tough and complicated to handle big query thats why we’re moving to Laravel eloquent relationships.

Model Query Using Relationships

$student_marks = student::find(1);
dd($student_marks->mark1);

 
The above example is a simple example of eloquent relationships and we can reduce the first query into a simple one.

One To One Relationships

Here we are creating 2 tables as “Users” and “Phones” so now we can see one to one relationships of this tables using hasone() and belongsto().
For this, we need to create the table using migrations

Related: Laravel API – How to Build REST API with Laravel 5.5 / Laravel 5.6

 

How To Create Migrations

 

users table will be created by using
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Phones table will be created by
Schema::create('phones', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('phone');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});

After creating migrations, we need to create a model for each table. Hope you already know that usually the laravel table name will be ending with “s”(Plural) and model name will be without ‘s’ so you can also maintain the same standards.

User Model

 

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
Phone Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
For Creating records
$user = User::find(1);
$phone = new Phone;
$phone->phone = '9080054945';
$user->phone()->save($phone);
$phone = Phone::find(1);
$user = User::find(10);
$phone->user()->associate($user)->save();
Now we can get our records by
$phone = User::find(1)->phone;
dd($phone);
$user = Phone::find(1)->user;
dd($user);

 

One To Many Relationships

Here we will use hasMany() and belongsTo() for one to many relationships. Now we are creating two tables, posts and comments, and we will be having a foreign key towards posts table.

Also Read: Generate Charts And Graphs Using Laravel

 

Migrations For Posts And Comments Table

 

Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});

Let’s create Post Model and Comment Model

Post Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}

Now we can create records through Comments Model,

$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi Harikrishnan";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "How are You?";
$comment2 = new Comment;
$comment2->comment = "Where are you?";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();
Now we can get records
$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);

 

To create records

 

$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi Harikrishnan";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "How are You?";
$comment2 = new Comment;
$comment2->comment = "Where are you?";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();

 

To get records

 

$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);

Many To Many Relationships

Many to many is little bit different and complicated than the above two.
In this example, I will create users, roles, and role, users_tables, here each table will be connected each other using the foreign keys.
Using belongsToMany() we will use see a demo of Many to many relationship
Create Migrations

Schema::create('users', function (Blueprint $table) {
   $table->increments('id');
   $table->string('name');
   $table->string('email')->unique();
   $table->string('password');
   $table->rememberToken();
   $table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
   $table->increments('id');
   $table->string('name');
   $table->timestamps();
});
Schema::create('role_user', function (Blueprint $table) {
   $table->integer('user_id')->unsigned();
   $table->integer('role_id')->unsigned();
   $table->foreign('user_id')->references('id')->on('users')
       ->onDelete('cascade');
   $table->foreign('role_id')->references('id')->on('roles')
       ->onDelete('cascade');
});

 

How To Create Models In Many To Many Relationships

 

User Model

 

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
   use Notifiable;
   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
       'name', 'email', 'password',
   ];
   /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
   protected $hidden = [
       'password', 'remember_token',
   ];
   /**
    * The roles that belong to the user.
    */
   public function roles()
   {
       return $this->belongsToMany(Role::class, 'role_user');
   }
}

 

Role Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
   /**
    * The users that belong to the role.
    */
   public function users()
   {
       return $this->belongsToMany(User::class, 'role_user');
   }
}

 

UserRole Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserRole extends Model
{
}

 

To Create Records

 

$user = User::find(2);
$roleIds = [1, 2];
$user->roles()->attach($roleIds);
$user = User::find(3);
$roleIds = [1, 2];
$user->roles()->sync($roleIds);
$role = Role::find(1);
$userIds = [10, 11];
$role->users()->attach($userIds);
$role = Role::find(2);
$userIds = [10, 11];
$role->users()->sync($userIds);

 

To Retrieve Records

 

$user = User::find(1);
dd($user->roles);
$role = Role::find(1);
dd($role->users);

Hence laravel Eloquent is more powerful and helps to build relationships easily compared to native query. With eloquent relationship we can easily connect the tables each other and we also have three more relationships in laravel but we will see more about it in our next blog as part 2 so stay tuned with us!

  • Has Many Through Relationship
  • One To Many Polymorphic
  • Many To Many Polymorphic

Similarly you can learn more interesting blogs on latest technologies, never miss out anything from our largest blog portal where you can get continuous blog updates & latest posts about all the latest technologies which would be perfect for your 15 minutes tea break! In case if you’re a newbie then don’t forget to subscribe us to get the latest updates from diverse technologies. What else guys hit the subscribe link and go crazy over learning. For more inquires reach us via info@agiratech.com

Harikrishnan R

Around 3 years of experience he scored intense knowledge on PHP, Laravel, Symfony, Angular & ensuring to learn the new & best methods to bring excellence in building applications. Also he has some aspiring dream to do Doctorate and the strange reason behind this will definitely leave a smile on your face! Yeah because he just loves writing his name as Dr. Harikrishnan