Relationships in Laravel

 Relationships in Laravel 

In Laravel database tables are often related to another table. Before starting a relationship topic, There are two ways to communicate with tables and perform operations.

Type of Relationships.

  1. Query Builder
  2. Eloquent ORM ( Object Relationship Model)

 1. Query Builder

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It is used to perform database operations in your application and works perfectly with all of Laravel's supported database systems.

Features of Query Builder

   a) It interacts with multiple databases like, SQLlite, Mysql, Postgresql etc.
   b) It protects the application against SQL injection attacks because it supports PDO ( PHP Data Objects ).
   c) We can write SQL queries in the controller we can see the example below. 

Example1

<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller{
publicfunction index(){
      $data= DB::table('students')->get();
      dd($data);
   }
}
?>

Output
Student Records
Here we have to write "use Illuminate\Support\Facades\DB;" after namespace in top section. After that we can write query..

2. Eloquent ORM

The Eloquent ORM stands for an object relation mapper and it is a technique to access objects without having to consider how those objects are related to their source. , it is by default built in Laravel. It is used to handle database records by data as objects. 

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" used to interact with that table.

When we use Eloquent, each database table has a corresponding "Model" used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.

Relationships Laravel

In Laravel relationships are defined as methods on your Eloquent model classes. Since relationships also provide powerful “query builders”, it is used to define the relationships as the method provides powerful method chaining and querying capabilities.  

In Laravel Eloquent makes managing and working with these relationships easy. but, before diving too deep into using Laravel relationships, let's learn how to define each type of relationship supported by Eloquent. It provides various types of  common relationships:

Types of Relationship

  1. One To One
  2. One To Many
  3. Many To Many
  4. Has One Through
  5. Has Many Through
  6. One To One (Polymorphic)
  7. One To Many (Polymorphic)
  8. Many To Many (Polymorphic)

In the given above relationship we will learn not all but basics we will cover for those who started learning relationships in Laravel.

  1. One To One
    In Laravel one to one relationship is a basic database relationship, it means a relationship between two tables.  we will retrieve the single records.
    In one to one relationship we will use the hasOne() method that returns the result.The hasOne() method is available in our model via the model's “Illuminate\Database\Eloquent\Model base” class.

Example of one to one relationship in Laravel

In this example, we will create two tables “Company” and “Member” and make a relation using foreign key and another way also.
We will follow the given steps:

  1. Create two model, controllers and migration.
    php artisan make:model Student -crm;
    php artisan make:model Training -crm;
  2. Open the migration file and put the below code
  3. Student Table
     public function up(){
        Schema::create('students', function (Blueprint $table) {
              $table->id();
              $table->string("name");
              $table->string("mobile");
              $table->timestamps();
       });
     }
  1. Training Table
public function up(){
   Schema::create('trainings', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
        $table->foreignId('student_id');
    });
}
  1. Now run migrate command.

     Php artisan migrate

  1. Now Open Students model and put in the following code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model{
  use HasFactory;
  public function Training(){
return $this->hasOne(Training::class);
   }
}
  1. Now Open the Trainings model and put in the following code.
<?php
namespace App\Models;
use App\Models\Training;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Training extends Model{
   use HasFactory;
}

 

 

  1. Now open Student Controller and add Training
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use App\Models\Training;
use Illuminate\Http\Request;
class StudentController extends Controller{
public function index(){ 
     $data= Student::with('Training')->get();
        return $data;
    }
}


Here we have used with() function and we will call Student model function which is “Training”. You can check in student model.

  1. Now create Route:

      Route::get('students',[StudentController::class,'index']);

  1. Open Web Url and check the outputs

Output  

  1. One To Many
  2. Many To Many

Ref: if we want to know more about Relationship in Laravel  Click here for official Website of Laravel.