Laravel Migrations and Models, Handle one to one, one to many and many to many relations in these layers
Tags: php, laravel, migration, models
Published: 2020-06-16 15:41:29

First of all we make model and migration files that we want
‍‍‍‍```
php artisan make:migration create_users_table
php artisan make:migration create_phones_table
php artisan make:migration create_books_table
php artisan make:migration create_roles_table
php artisan make:migration create_role_user_table
```

### And then you can make models in the other commands
```
php artisan make:model User
php artisan make:model Phone
php artisan make:model Book
php artisan make:model Role
``` 

## Common Column Types

#### It can be id and it is Alias of $table->bigIncrements('id').
```php
$table->id();
```

#### It can be use for foreign id in a table and it is Alias of $table->unsignedBigInteger('user_id').
```php
$table->foreignId('user_id');
```

#### 	BOOLEAN equivalent column.
```php
$table->boolean('confirmed');
```


#### 	DATE equivalent column.
```php
$table->date('created_at');
```


####	DATETIME equivalent column with precision (total digits).
```php
$table->dateTime('created_at', 0);
```

####	ENUM equivalent column.
```php
$table->enum('level', ['easy', 'hard']);
```


#### INTEGER equivalent column.
```php
$table->integer('votes');
```


#### 	JSON equivalent column.
```php
$table->json('options');
```


#### 	LONGTEXT equivalent column.
```php
$table->longText('description');
```


#### 	MEDIUMTEXT equivalent column.
```php
$table->mediumText('description');
```


#### 	TEXT equivalent column.
```php
$table->text('description');
```


#### 	VARCHAR equivalent column with a length.
```php
$table->string('name', 100);
```

## Column Modifiers 

#### 	Specify a "default" value for the column
```php
->default($value)
```

#### 	Allows (by default) NULL values to be inserted into the column
```php
->nullable()
```


#### 	Place the column "after" another column (MySQL)column
```php
->after('column')
```

#### 		Place the column "first" in the table (MySQL)
```php
->first()
```

#### 	Set INTEGER columns as UNSIGNED (MySQL)
```php
->unsigned()
```


## Foreign Key Constraints
```php
Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
```

## Now let's start with one to one ralation
## one to one
Imagine that you have user table and phone table and which user has only one phone

### 2020_06_15_00_create_users_table.php
```php
    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();
        });
    }
```

### 2020_06_15_01_create_phones_table.php
```php
    public function up()
    {
        Schema::create('phones', function (Blueprint $table) {
            $table->id();
            $table->string('phone_number');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }
```

### User.php 
```php
<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}
```

### Post.php 
```php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
```

### How use it
```php
$phone = User::find(1)->phone;
```

## one to many
For example we have book table and each user can have many books

### 2020_06_15_03_create_books_table.php
```php
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }
```

### User.php
```php
<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }

    public function books()
    {
        return $this->hasMany('App\Book');
    }
}
```


### Book.php
```php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
```

## How to use it
```php
$books = App\User::find(1)->books;

foreach ($books as $book) {
    //
}
```

```php
$book = App\Post::User(1)->books()->where('name', 'foo')->first();
```
## Or you can give user from book
```php
$book = App\Comment::find(1);

echo $book->user->name;
```

## Many To Many
For example imagine user's roles 
Each user can have many roles and each role can be assigned to many users

### 2020_06_15_03_create_roles_table.php
```php
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
```

### 2020_06_15_03_create_role_user_table.php
```php
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('role_id');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->timestamps();
        });
    }
```

## How to use it
```php
$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}
```

```php
$roles = App\User::find(1)->roles()->orderBy('name')->get();
```
## Or you can give user from book
```php
$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}
```

Feel free to ask any questions 🙂🙃