How to use Laravel Eloquent Relations

The Right Software > Blog > Laravel > How to use Laravel Eloquent Relations
How to use Laravel Eloquent Relations - Introduction and usage

For databases that work on basis of relations i.e rdbms you have to define structure of your database before inserting any data to it . World’s most famous MySQL is a relational database. Other famous RDBMS are MSSQL, Oracle, Microsoft Access and SQLite. In these databases, a collection of similar data is called a table. Primary key of one table is the foreign key in other table. Frankly, RDBMS is a big subject and outside the scope of this discussion. However, to understand how Laravel Eloquent relations, you need to have an intermediate level knowledge of table structure and relation databases.

This tutorial is on how you can use power of Eloquent to help you develop Laravel applications faster.

There are three basic types of relationships one-to-one, one-to-many and many-to-many. In custom PHP or in frameworks that work on basis of Active Record pattern you have to manage the relations using joins while in Laravel you have that option too but you can manage all those relations in a very simple way using eloquent models.

Eloquent models are not like normal models where you have to write all the queries in different functions and you are limited to those functions, Eloquent model is like database table and it comes with a large set of handy functions like first, find, create and firstOrNew etc. These simple Eloquent models also give you an option to manage all of your database relations on application level.

Before going into its implementation, if you don’t have a project installed then install one on your local machine and create migrations for users, phone, posts and companies table using following command.

php artisan make:model User -m
php artisan make:model Phone -m
php artisan make:model Post -m
php artisan make:model Company -m
php artisan make:migration create_company_user_table

All of the above commands will create the models with migrations, now go to each migration and update them for these columns. users table should have id(int), email(varchar), first_name(varchar), last_name(varchar) and timestamps, phones table should have id(int), company(varchar), phone_number(varchar), user_id(int) as foreign key of users table and timestamps, posts table should have id(int), title(text), description(text), user_id(int) as foreign key of users table and timestamps, companies table should have id(int), name(varchar) and timestamps, and company_user table should have id(int), company_id(int) as foreign_key of company table user_id(int) as foreign key of users table and timestamps.

>nbsp;

banner hire laravel framework development services

>nbsp;

One-to-one Relation

In one-to-one relation two tables are related in a way that a record in one table can have only one record against it in the other table. we will implement that relation between a users and phones table using eloquent models. so go to User model and add following function to it.

public function phone() {
    return $this->hasOne('App\Phone');
}

Now go to Phone model and add below function to it.

public function user() {
 return $this->belongsTo('App\User');
 }

hasOne function also accepts second and third parameter as foreign and primary key, if doesn’t specify then laravel will assume it as adding _id to name of your model as foreign key like in above case it will assum user_id and id as primary key. while in belongsTo function the second argument is primary and third param as foreign key. Thats it your relations are defined now lets do crud operations on it, if you just want to check how it works then open command prompt on your system and redirect to your project root directory and run the command

php artisan serve

In the window opened run the following code and you would be able to see Laravel Eloquent relations in action.

 $user = \App\User::create(['email' => '[email protected]' ,'first_name' => 'abc', 'last_name' => 'def']);
 $user->phone()->create(['company' => 'abc', 'phone_number' => '+12025550150']);
 $user->phone()->first();
 $user->phone()->first()->update(['phone_number' => '+12025550190']);
 $user->phone()->first()->delete();

Check your db while executing each line of code of above.

>nbsp;

One-to-many Relation

In one to many relation between two tables in db one table record can have many record related to it in other table, lets implement it between users and posts table, one user can have many posts and a post is related to only one user. To implement it in eloquent go to User model and add the following function to it.

public function posts() {
     return $this->hasMany('App\Posts');
 }

Now go to the Posts model and add the following function to it.

public function user() { 
     return $this->belongsTo('App\User');
 }

Thats it your relations are defined now lets do crud operations on it, open command prompt on your system and redirect to your project root directory and run the command

php artisan serve

In the window opened run the following code and you would be able to see Laravel Eloquent relations in action.

$user = \App\User::find('1');
 // to create posts against a user
 $user->posts()->create(['title' => 'Example title', 'description' => 'some example description for post']);
 //to get all posts of a user
 $user->posts()->get();
 //to update post of id 1 against a user
 $user->posts()->find('1')->update(['title' => 'updated title']);
 //to delete post of id 1 against a user
 $user->posts()->find('1')->delete();
 // you can use inverse relation too
 $post = \App\Post::find('1');
 //to do crud operations on user against above post
 $post->user()->get();
 $post->user()->update(['first_name' => 'jeff']);
 $post->user()->delete();

>nbsp;

Many-to-many Relation

In many to many relation any record on both tables in relations can have many related records in other table, for this relation youn need a pivote table which have data about the relations of two tables. For such relations in most of frameworks you have to write two joins to main table, in laravel its far more easier
to implement and manage. To implement this relation between users and companies tables using company_user table go to User model and add below function to it.

public function companies() {
     return $this->belongsToMany('\App\Company', 'company_user');
}

and add below function to Company table.

public function users() {
      return $this->belongsToMany('\App\User', 'allowed_countries');
 }

In belongsToMany function second param is name of pivote table and you are all set to go, lets do some crud operations on it.

$user = \App\User::create(['email' => '[email protected]', 'first_name' => 'abc', 'last_name' => 'def']);
 \App\Company::create([ ['name' => 'trs1'], ['name' => 'trs2'] ]);
 //you can attach or detach a company to a user use company id
 $user->companies()->attach(['1', '2']);
 $user->companies()->detach('1');
 // to retrieve companies to which user belongs use below function
 $user->companies()->get();
 //you can also use the reverse relation like if you want all the users in a company
 $company = \App\Company::find('1');
 $company->users()->get();
 //you can use sync function to remove all the previous companies of a user and add the new companies id's array
 $user->companies()->sync(['1','2']);

I hope that you understand this tutorial and have a better handle on Laravel Eloquent Relations. If you need help or explanation at any point, do give us a shout. You can also Hire Laravel Developers from The Right Software to take care of your web projects.

Cheers.

Start a Project with The Right Software