Laravel Eloquent Relationships

  • Cubettech
  • Laravel Development
  • 9 years ago
Laravel Eloquent Relationships

Laravel-Model

Eloquent ORM is an Object Relational Mapper that enables us to define relationship with the model, such that once the relationship is defined we can perform database manipulation without explicit query.

Relationship type -:

  1. OnetoOne
  2. OnetoMany
  3. ManytoMany
  4. HasManyThrough
  5. Polymorphic one-to-one/one-to-many

Implementation

1.Install laravel
2.create new database in mysql(blog)
3.update db details in config/database.php

one-to-one relation
Example : schema

Implementation of One to One Relation in Laravel Eloquent Relationships

Here post_id is the foreign_key of Post_Content, So in order to create the relation, first we need to create the model

Implementation of One to One Relation in Laravel Eloquent Relationships Image 2

Now we can access the data using $blog->blog_content

One-to-Many

For each blog there is only a single author and a single author can have many post(one-to-*).

Implementation of One to Many Relation in Laravel Eloquent Relationships Image 2

And now let’s establish a one-to-* relation using hasMany functions.

$blog_author->post we get all the posts of a single author. Here we need to get the author details of a single post, for each post there is a single author, within the Post model including belongsTo relation.

In the post, we get the details of author using $post->author->author_name

In Author, we can loop through all the post of an author using $author->post

Implementation of One to Many Relation in Laravel Eloquent Relationships Image 2

Many-To-Many

Each post have many tag and each tag can have many post.

Implementation of Many to Many Relation in Laravel Eloquent Relationships

Laravel Model Relationships

Here all the above methods used to read data, While creating a new post we need to insert data to the Post, Content, Author etc. we can perform this using query builder save()

$post = Post::create(array(‘title’ => Input::get(‘title’));// insert into table post
$text = Text::create(array(‘text’ => Input::get(‘text’)); // insert into table content
$post->text()->save($text);

Conclusion

This article includes the fundamentals of Eloquent ORM model. Eloquent ORM implementation is really fast and the interaction with the database is very simple.

Know More About This Topic

Got a similar project idea?

Connect with us & let’s start the journey!

Questions about our products and services?

We're here to support you.

Staff augmentation is a flexible workforce strategy companies adopt to meet specific project needs or address skill gaps.

Begin your journey!
Need more help?