Site icon FahmidasClassroom

How to create one-to-one relationship in the database using Laravel

One To Many

Create one-to-one relationship in the database using Laravel

Steps:

1. Create a migration file for adding a new table profile

php artisan make:migration create_table_profile

2. Add the following code in the up function


Schema::create('profiles', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->string('telephone');
    $table->timestamps();

});


3. Run the migrate command

php artisan migrate

4. Add User Model class and add the following code.


public function profile()
{
      return $this->hasOne('todoparrot\Profile');
}

05. Create profile model and add the following method to create belongs to relation


public function user()
{
     return $this->belongsTo('todoparrot\User');
}

6. Create or edit UserController and the following code to search profile data using user id


$user = User::find(2)->profile->telephone;
echo “Phone :“ . $user;

7. Add the route and run the code

8. Creating a One-to-One Relation


$profile = new Profile;
$profile->telephone = '614-867-5309';
$user = User::find(212);
$user->profile()->save($profile);

9. Deleting a One-to-One Relation


$user = User::find(2);
if($user->delete()) echo "Data is Deleted successfully";
else echo "error in deleting";

10. Add the following code in the UserController to retrieve user record based on Profile data.


$firstname = Profile::where('telephone', '01927863545')->get()->first()->user->first_name;
echo $firstname;

The full steps are shown in the following video tutorial.

Good Luck

 

Exit mobile version