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

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

azibom profile image Mohammad Reza ・3 min read

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').

$table->id();

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

$table->foreignId('user_id');

BOOLEAN equivalent column.

$table->boolean('confirmed');

DATE equivalent column.

$table->date('created_at');

DATETIME equivalent column with precision (total digits).

$table->dateTime('created_at', 0);

ENUM equivalent column.

$table->enum('level', ['easy', 'hard']);

INTEGER equivalent column.

$table->integer('votes');

JSON equivalent column.

$table->json('options');

LONGTEXT equivalent column.

$table->longText('description');

MEDIUMTEXT equivalent column.

$table->mediumText('description');

TEXT equivalent column.

$table->text('description');

VARCHAR equivalent column with a length.

$table->string('name', 100);

Column Modifiers

Specify a "default" value for the column

->default($value)

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

->nullable()

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

->after('column')

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

->first()

Set INTEGER columns as UNSIGNED (MySQL)

->unsigned()

Foreign Key Constraints

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

    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

    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

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

namespace App;

use Illuminate\Database\Eloquent\Model;

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

How use it

$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

    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

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

namespace App;

use Illuminate\Database\Eloquent\Model;

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

How to use it

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

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

Or you can give user from book

$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

    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

    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

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

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

Or you can give user from book

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

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

Feel free to ask any questions 🙂🙃

Posted on by:

azibom profile

Mohammad Reza

@azibom

azibom ... bom ... bom

Discussion

markdown guide