Laravel Migration

Database

SQlite

Create empty sqlite database 1

sqlite3 file.db "VACUUM;"

Table

Check table

if (!Schema::hasTable('table_name')) {
	// Opt tables
}

Check table column

if (Schema::hasColumn('table_name', 'column_name')) {

}

Create table

Schema::create('table_name', function (Blueprint $table) {
    $table->increments('id');

    $table->integer('foreign_id')->unsigned();
    $table->foreign('foreign_id')->references('id')->on('foreign_table')->onDelete('cascade');

    $table->string('key');
    $table->text('value')->nullable(true);
    $table->timestamps();
});

Create table with foreign key

Schema::create('link_product_retailer', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('product_id')->unsigned()->nullable();
    $table->integer('retailer_id')->unsigned()->nullable();
    $table->foreign('product_id')->references('id')->on('products');
    $table->foreign('retailer_id')->references('id')->on('retailers');
});

Foreign Key

Drop Foreign Key

Schema::table('table', function(Blueprint $table){
    $table->dropForeign('foreign_name');
});

Index

Add index

Schema::table('table', function(Blueprint $table) {
    $table->index(['col1', 'col2']);
});

Remove index

Schema::table('table', function(Blueprint $table) {
    $table->dropIndex('index_name');
});

Rename table

Schema::rename('table_name', 'new_table_name');

Drop table

Schema::dropIfExists('table_name');
 // DROP TABLE IF EXISTS `table_name`;

View

Create view

DB::statement("
        CREATE 
            OR REPLACE 
            SQL SECURITY INVOKER
        VIEW `view_name` AS

        SELECT * 
        FROM `table`
        ")

Drop view

DB::statement('DROP VIEW IF EXISTS `view_name`;');

Table row

\App\Models\Model::where( [
    'key' => 'value'
])->first()->update([
    'key' => 'value'
    ],
]);

Model

Relationship

graph LR
A[Master] -- one to many --> B[Slave]
$master->hasMany(Slave::class);
$slave->belongsTo(Master::class);
graph LR
E[Employer] --> L((employer_staff))
S[Staff] --> L((employer_staff))
$employer->belongsToMany(Staff::class)
$staff->belongsToManu(Employer::class)
graph LR
U[User] -- one to one --> N[Name]
$user->hasOne(Name::class)
$name->hasOne(User::class)

Factory

create persists to the database while make just creates a new instance of the model. Laravel create method is created the model instance and save data in the database. make function has created the instance of the class. 2