Skip to main content

Eloquent Relationship Explained (ONE TO ONE)

One to one relationship:


Suppose you have two tables users and addresses:

Users table:
id,name,email

Addresses table:
id,name, user_id

In the address table the user_id will come from the users table. Be careful about the naming convention.

Your Model name is User so table name is users so to get id from users table to addresses table you have to write according to the model name in the field of address like user_id.


So to declare one-to-one relationship:
Just think that user can have only one address. So,  go to User model and write:

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

here as this is one to one we are using singular function name which is address().

Store:

$user->address()-> save($address);

[Here, $user is finding the user by id, and $address is saving the requested address]

Show:
To show the address name

$user->address->name;

Update:
$address = Address::whereUserId(1)->first();
$address->name="Feni, Bangladesh";
$address->save();

Delete:
To delete address:

$user-> address()-> delete();

Thanks for reading.

Comments

Popular posts from this blog

Laravel Vuejs Basic Setup

In this article we will see how to setup vue with laravel. 1) Create a laravel project: laravel new laravue 2) In web.php create a temporary route:  Route :: get ( '/test' ,  function  () {      return   view ( 'welcome' ); }); So, when you will see the welcome page once you hit the  http://laravue.test/test  url. 2) In terminal run:  npm install 3) npm install vue (In package.json file you will see that vue dependency has been added successfully) 4) Now go to resources -> js -> app.js file. Here we will have to load the vue. write the following lines in app.js.  require ( './bootstrap' ); window . Vue  =  require ( 'vue' ); const   app  =  new   Vue ({      el :   '#app' }); (Here, vue js will execute and control anything that will be inside the app id. So, for our example  let's put the app id inside the welcome view). So, inside welcome.blade.php 's body...