I have users
and phone
table and I made one-to-one relationship in laravel, that's working perfectly but if I try to add data (foreign key user_id) manually to phone table without reference of any user(id), it also work.
In mysql(phpmyadmin), there is no foreign key relation built after the migration.
So I want to ask, what are the advantages of foreign key if it does't put any constraints in db tables or if is there any way to add these constraints using laravel, kindly let me know.
Code snippets
app/Phone.php
public function user(){
return $this->belongsTo('App\User');
}
app/User.php
public function phone(){
return $this->hasOne('App\Phone');
}
routes/web.php
Route::get('/', function () {
$user = factory(\App\User::class)->create();
$phone=new \App\Phone;
$phone->phone = '123456789';
$phone->user_id = '1';
$user->phone()->save($phone);
});
Phone (migration)
public function up()
{
Schema::create('phones', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('phone');
$table->unsignedBigInteger('user_id')->index();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
Users table does not have any user with id 10 but this also works and add data to phone (user_id)
$phone->phone = '123456789';
$phone->user_id = '10';
$phone->save();