Laravel foreign Key management

PHOTO EMBED

Thu Dec 22 2022 12:27:38 GMT+0000 (Coordinated Universal Time)

Saved by @ahmad007 #laravel #ajax

1. add the following code in laravel migrations to set foreign key
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
or if you want to delete the foreign id data also
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
here 'customers' is the table of id here we are considering as foreign id
2. Now in the customer model as the following function
public function orders(){
        return $this->hasMany(Order::class, 'customer_id');
    }
3. In the order model add the following function
public function customer(){
        return $this->belongsTo(Customer::class, 'customer_id', 'id');
    }
content_copyCOPY