. Hello, world!

 

 

Paivot Table:

when we use many to many relationship we use pivot table

→Connect your database in env file

php artisan make:migration create_doctors_table

 php artisan make:migration create_hospitals_table

 php artisan make:migration create_doctor_hospital_table

 

→now in doctor migration

$table→string('name);

→now in hospital table

$table→string('name);

→now in our pivot table

$table→foreignID('docotor_id')→constrained();
$table→foreignID('hospital_id')→constrained();
$table→boolean('isPartTime')→default(false);

→php artisan migrate

→now lets create seeder

php artisan make:model Doctor

php artisan make:model Hospital

 

→make factory

php artisan make:factory DoctorFactory

php artisan make:factory HospitalFactory

→now in doctor factory

return[
‘name’=>fake()→name();
]

→now in hospital factory

 

return[
‘name’=>'Hospital'.fake()→text(20);
]

→now in doctor model

use App\Models\Hospital;
publuc function hospitals(){
return $this→belongsToMany(Hospital::class)->withPivot('default'); //here we can get all pivot table couloumns
}

→now in database seeder

use app\models\Hospital;
use app\models\doctor;
Doctor::factory(5)→create();
Hospital::factory(10)→create();

→now seed

php artisan db:seed;

 

→now in database seeders again

$doctors =Doctor::all();
foreach($doctors as $doctor)
{
$doctor→hospitals()→attach(
Hospital::inRandomOrder()→take(rand(1,4)→pluck('id'),
[
‘default’=>rand(0,1), //extra table Couloumns
]
);
);
}

 

→now seed again

php artisan db:seed

 

→Now How to retrive data from pivot table

→create a controller and view

php artisan make:controller HomeController

→now in resource create a view file doctor.blade.php

→Now in your Home Controller

public function index()
{
Doctor::with('hospitals')→get();
return view('docotr',['doctors'=>$doctor])
}

→now in your view file

@foreach($doctors as $doctor)
<h1>{{$doctor→name}}</h1>
@foreach($doctor→hospitals as $hospital)
{{$hospital→name}}
//Display pivot table
{{$hospital->pivot->default}} //default here is pivot table couloumn
@endforeach
@endforeach

 

→How to rename pivot attribute 

 

use App\Models\Hospital;
publuc function hospitals(){
return $this→belongsToMany(Hospital::class)->withPivot('default')->as('yourCustomName'); //here we can get all pivot table couloumns
}