One to one Relation in laravel..


1.make laravel project setup.

composer create-project laravel/laravel orm


2.Start server in laravel.. 

 php artisan serve


3.Make model and migration 

 php artisan make:model Contact -m                      //-m for migration ..


4. Add field in Contact Migrations

   $table->string('address');

   $table->string('phone');

   $table->foreignId('user_id')->constrained()->onDelete('cascade');  //Make foreign key..


5. for make table:

   php artisan migrate

 //php artisan migrate:fresh for new data of table schema reinsert ..


6. for data seed  in table 

   php artisan make:seeder UserSeeder


7. insert value in Userseeder

    public function run()

    {   

        User::create([

            'name'=>'test',

            'email'=>'test@gmail.com',

            'password' => bcrypt('password')

        ]);


        Contact::create([

            'user_id'=>1,

            'phone'=>'6665552221',

            'address' =>'address test..'

        ]);

    }


8. Contact Model m fill

 protected $fillable  = ['user_id','phone', 'address'];


9.DatabaseSeeder m 

$this->call(UserSeeder::class);


10. use command for data insert in table

php artisan db:seed


11. Use in User Model

 public function contact(){

        return $this->hasOne(Contact::class);

    }


12.Use in Contact Model

   public function User(){

           return $this->belongsTo(User::class);  //inverse Relations

}


13. for User model 

use App\Models\User;

$user = User::with('contact')->first();

return $user->all();


14. for Contact Model

use App\Models\Contact;

$contact = Contact::with('user')->first();

return $contact->all();



15. Make controller and code .. Full code of controller ..




<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Models\User;

use App\Models\Contact;


class TestController extends Controller

{

    public function index(){

        $user = User::with('contact')->first(); //contact for show one to one relations

        // return $user->all();

        // return $user->contact;

        // return $user->contact->address;

        // dd($user->toArray());


        //use Reverse 

        $contact = Contact::with('user')->first();

        return $contact->all();


    }

}




16. Make Route ..

Route::get('/',[\App\Http\Controllers\TestController::class,'index']);




   


Comments

Popular posts from this blog

My Sql Query ..

Interview question laravel.