Laravel 9 One to One Relationship Example (ok)

https://www.itsolutionstuff.com/post/laravel-9-one-to-one-relationship-exampleexample.html

Ví dụ 1:

app\Models\Phone.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
// use App\Models\User;
class Phone extends Model {
  use HasFactory;
  public function user() {
    return $this->belongsTo(User::class);
  }
}

app\Models\User.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  public function phone() {
    return $this->hasOne(Phone::class);
  }
}

app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Phone;
class UserController extends Controller {
  public function index(Request $request) {
    $phone = User::find(6)->phone;
    dd($phone);
    // $user = Phone::find(1)->user;
    // dd($user);
  }
}

database\seeders\PhoneSeeder.php

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Phone;
class PhoneSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Phone::factory()->count(30)->create();
    }
}

database\factories\ProductFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Product;
class ProductFactory extends Factory
{
    protected $model = Product::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'category_id' => $this->faker->numberBetween(1, 4),
            'brand_id' => $this->faker->numberBetween(1, 4),
            'product_img' => 'images/product/1.jpg',
            'product_title' => $this->faker->text,
            'product_content' => $this->faker->text,
            'product_price' => $this->faker->numberBetween(200, 1000),
            'product_status' => $this->faker->numberBetween(0, 1),
        ];
    }
}

database\migrations\2022_08_24_095704_create_table_phones_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTablePhonesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phones', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users');
            $table->string('phone');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('phones');
    }
}

database\migrations\2014_10_12_000000_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        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()
    {
        Schema::dropIfExists('users');
    }
}

routes\web.php

// Test
Route::get('/users', [UserController::class, 'index'])->name('index');

app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Phone;
class UserController extends Controller {
  public function index(Request $request) {
    // $phone = User::find(6)->phone;
    // dd($phone);
    $user = Phone::find(1)->user;
    dd($user);
  }
}

Tham khảo bên Laravel 9 One to Many Eloquent Relationship Tutorial

Source code: https://app.gitbook.com/o/-LVfVRgJVnpA6bttpEFT/s/-MCBeDUD-PK_RF-YgJRe/laravel-9-many-to-many-eloquent-relationship-tutorial

Hi Dev,

This tutorial will provide an example of laravel 9 one to one relationship example. you'll learn laravel 9 eloquent one to one relationship. We will look at example of laravel 9 hasone relationship example. if you want to see an example of laravel 9 belongsto relationship example then you are the right place. So, let's follow a few steps to create example of laravel 9 belongsto one to one relationship.

One to One model relationship is very simple and basic. you have to make sure that one of the tables has a key that references the id of the other table. we will learn how we can create migration with foreign key schema, retrieve records, insert new records, update records, etc.

In this example, I will create a "users" table and the "phones" table. both tables are connected with each other. now we will create one to one relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see the database table structure below the screen.

One to One Relationship will use "hasOne()" and "belongsTo()" for relation.

Create Migrations:

Now we have to create migration of "users" and "phones" table. we will also add foreign key with users table. so let's create like as below:

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()
    {
        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()
    {
        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()
    {
        Schema::create('phones', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users');
            $table->string('phone');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('phones');
    }
};

Create Models:

Here, we will create User and Phone table model. we will also use "hasOne()" and "belongsTo()" for relationship of both model.

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;
  
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(Phone::class, 'foreign_key', 'local_key');
     *
     * Example: return $this->hasOne(Phone::class, 'user_id', 'id');        
     */
    public function phone()
    {
        return $this->hasOne(Phone::class);
    }
}

app/Models/Phone.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Phone extends Model
{
    use HasFactory;
  
    /**
     * Get the user that owns the phone.
     * 
     * 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)
    {
        $phone = User::find(1)->phone;
  
        dd($phone);
    }
}
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Phone;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $user = Phone::find(1)->user;
  
        dd($user);
    }
}

Create Records:

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

Read Also: How to Create Custom Error Page in Laravel 9?

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

I hope you understand of one to one relationship...

Last updated