DEV Community

Cover image for Laravel Migrations and Models, Handle one to one, one to many and many to many relations in these layers
Mohammad Reza
Mohammad Reza

Posted on

Laravel Migrations and Models, Handle one to one, one to many and many to many relations in these layers

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Common Column Types

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

$table->id();
Enter fullscreen mode Exit fullscreen mode

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

$table->foreignId('user_id');
Enter fullscreen mode Exit fullscreen mode

BOOLEAN equivalent column.

$table->boolean('confirmed');
Enter fullscreen mode Exit fullscreen mode

DATE equivalent column.

$table->date('created_at');
Enter fullscreen mode Exit fullscreen mode

DATETIME equivalent column with precision (total digits).

$table->dateTime('created_at', 0);
Enter fullscreen mode Exit fullscreen mode

ENUM equivalent column.

$table->enum('level', ['easy', 'hard']);
Enter fullscreen mode Exit fullscreen mode

INTEGER equivalent column.

$table->integer('votes');
Enter fullscreen mode Exit fullscreen mode

JSON equivalent column.

$table->json('options');
Enter fullscreen mode Exit fullscreen mode

LONGTEXT equivalent column.

$table->longText('description');
Enter fullscreen mode Exit fullscreen mode

MEDIUMTEXT equivalent column.

$table->mediumText('description');
Enter fullscreen mode Exit fullscreen mode

TEXT equivalent column.

$table->text('description');
Enter fullscreen mode Exit fullscreen mode

VARCHAR equivalent column with a length.

$table->string('name', 100);
Enter fullscreen mode Exit fullscreen mode

Column Modifiers

Specify a "default" value for the column

->default($value)
Enter fullscreen mode Exit fullscreen mode

Allows (by default) NULL values to be inserted into the column

->nullable()
Enter fullscreen mode Exit fullscreen mode

Place the column "after" another column (MySQL)column

->after('column')
Enter fullscreen mode Exit fullscreen mode

Place the column "first" in the table (MySQL)

->first()
Enter fullscreen mode Exit fullscreen mode

Set INTEGER columns as UNSIGNED (MySQL)

->unsigned()
Enter fullscreen mode Exit fullscreen mode

Foreign Key Constraints

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Enter fullscreen mode Exit fullscreen mode

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

    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();
        });
    }
Enter fullscreen mode Exit fullscreen mode

2020_06_15_01_create_phones_table.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();
        });
    }
Enter fullscreen mode Exit fullscreen mode

User.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');
    }
}
Enter fullscreen mode Exit fullscreen mode

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

How use it

$phone = User::find(1)->phone;
Enter fullscreen mode Exit fullscreen mode

one to many

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

2020_06_15_03_create_books_table.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();
        });
    }
Enter fullscreen mode Exit fullscreen mode

User.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');
    }
}
Enter fullscreen mode Exit fullscreen mode

Book.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

How to use it

$books = App\User::find(1)->books;

foreach ($books as $book) {
    //
}
Enter fullscreen mode Exit fullscreen mode
$book = App\Post::User(1)->books()->where('name', 'foo')->first();
Enter fullscreen mode Exit fullscreen mode

Or you can give user from book

$book = App\Comment::find(1);

echo $book->user->name;
Enter fullscreen mode Exit fullscreen mode

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

    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
Enter fullscreen mode Exit fullscreen mode

2020_06_15_03_create_role_user_table.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();
        });
    }
Enter fullscreen mode Exit fullscreen mode

How to use it

$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}
Enter fullscreen mode Exit fullscreen mode
$roles = App\User::find(1)->roles()->orderBy('name')->get();
Enter fullscreen mode Exit fullscreen mode

Or you can give user from book

$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}
Enter fullscreen mode Exit fullscreen mode

Feel free to ask any questions 🙂🙃

Top comments (1)

Collapse
 
franciscocaldeira profile image
Francisco • Edited

one to one example you use phone but created Post.php