One to One Relationship

Suppose You have a users table and passports table. Each user has only one passport number. On this case, you can one to one relationships

cd Directory
php artisan tinker
DB::table('users')->insert(['name'=>Amir,'created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('passports')->insert(['number'=>'998787545782','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime]);

Now you have to create model for user and passport

cd Directory
php artisan make:model user
php artisan make:model passport

user model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    public function passport(){
    	//return $this->hasOne('App\passport');
    	return $this->hasOne(Passport::class);
    }   
}

passport model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class mobile extends Model
{
    public function user(){
    	return $this->belongsTo(User::class);
    }
}

Retrieve the related record:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class HomeController extends Controller
{
    public function index(){
    	$passport_data = user::find(1)->passport;    	
    	return view('welcome',compact('passport_data'));
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s