User hasOne Phone

You should have two tables that look somehow like this:

User Table
id name
1 Bob
Phone Table
user_id phone
1 1234567

From the user class you can access his phone as


public function phone()
{
 return $this->hasOne('App\Phone');   
}

If you do not stick to Laravel naming conventions, you may have to explicitly state the column names:


 return $this->hasOne('App\Phone','user_id','id');   

And you can go back from your phone class to the related user:


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

Remove auto-increment column

Since we have a hasOne relation, there is need to keep a superfluous auto-increment column in your table.
Removing the auto-increment column makes your hasOne relationship more robust, because now its technically not possible to create duplicate phone rows for one user.

To get rid of the auto-increment column, make sure that in your migration file the line $table->increments(‘id’); is removed. Instead add the primary key


    $table->integer('user_id')->unsigned()->primary();

In your model you need to disable increments and point to the primary id column like this:


     class Phone extends Model
     {
      /**
      * The table associated with the model.
      *
      * @var string
      */
      protected $primaryKey   = 'user_id';
      public    $incrementing = false;

When ever a user is removed, its associated phone rows should be deleted automatically with foreign keys.

How to updateOrCreate?

There are many post out there, asking “How can I check if a relation exists, so that I know if I have to do an update or a create call?”. There is a nice trick how to use the UpdateOrCreate method for this job.


public function up()
{
 $user->phone()->updateOrCreate([],[ 'phone' => '123' ]);
}     

This will update the phone of the user to `123`, or create the phone, if it did not exist yet.

adam