How to use One to One Relationship in LARAVEL 10

Spread the love

Hello Guys,

In this concise guide, we delve into the concept of a One to One Relationship in Laravel 10. We’ll provide a robust example of a one-to-one relationship using Laravel 10, complete with hasOne and belongsTo relationship illustrations.

One-to-one relationships are a fundamental and uncomplicated database concept. They require that the key in one table corresponds to the id of another table, ensuring data consistency. In this article, we’ll explore how to create a database schema with a foreign key, fetch records, add new entries, update existing data, and more.

For our illustration, we’ll create two tables, “users” and “posts,” and establish a one-to-one connection between them using Laravel Eloquent Models. We’ll start with creating the necessary database migration, followed by model creation, data retrieval, and record insertion. Below, you can also view the database table structure for reference.

hasOne()” and “belongsTo()” will be used for relation in a one-to-one relationship.

Examples of One to One Relationship in LARAVEL 10:

Create Migrations:

Our next step involves executing a migration process for the ‘users’ and ‘posts’ tables. Alongside the ‘users‘ table, we will incorporate a foreign key. Let’s proceed with the following steps:

Also Read: How to use One to Many Eloquent Relationship in LARAVEL 10

users table migration:
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};
phones table migration:
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users');
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

Create Models:

In this tutorial, we’ll create a table model for Users and Posts, focusing on establishing a strong relationship between these two models using “hasOne()” and “belongsTo()” methods. This approach will help optimize your website for search engines and improve your SEO ranking.

Also Read: How to use Try Catch Exception Handling in API Using laravel 10

app/Models/User.php
<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Relations\HasOne;
  
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array

     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
 
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array

     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast.
     *
     * @var array

     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
  
    /**
     * Get the phone associated with the user.
     * 
     * Syntax: return $this->hasOne(Post::class, 'foreign_key', 'local_key');
     *
     * Example: return $this->hasOne(Post::class, 'user_id', 'id');        
     */
    public function posts()
    {
        return $this->hasOne(Post::class);
    }
}
app/Models/Post.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
  
class Post extends Model
{
    use HasFactory;
  
    /**
     * Get the user that owns the Post.
     * 
     * Syntax: return $this->belongsTo(User::class, 'foreign_key', 'owner_key');
     *
     * Example: return $this->belongsTo(User::class, 'user_id', 'id');        
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Retrieve Records:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $user = User::find(1);
  
        dd($user->posts);
    }
}

Also Read: how to integrate chatgpt API in laravel 10

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Post::find(1);
  
        dd($post->user);
    }
}

Create Records:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Post;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $user = User::find(1);
   
        $post = new Post;
        $post->title = 'post title';
        $post->slug  = 'post-title';
        $post->description  = 'post description';
           
        $user->post()->save($post);
    }
}

Also Read: How to use Multiple Database Connections in LARAVEL 10

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Post;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Post::find(1);
   
        $user = User::find(10);
           
        $Post->user()->associate($user)->save();
    }
}

Explore our Laravel blog section for insightful content and helpful tips.

Leave a Comment