Skip to main content

Mysql columns creation in laravel

List of columns 


$table->id(); // increment value
$table->string('title')->comment('this is blog title');
$table->string('slug')->unique();
$table->text('short_desc');
$table->longText('description');
$table->boolean('is_published')->default(false);
$table->integer('min_of_read')->nullable(true);
$table->enum('status', ['Active', 'Inactive']); 
$table->float('discount');
$table->smallInteger('type_id');
$table->date('start_date')->nullable();
$table->timestamps();
$table->foreign('created_by')->references('id')->on('users'); // introducing foreign key
$table->unsignedBigInteger('user_id'); //?
$table->decimal('latitude', 9, 6)->nullable(true);

// Let's say you want starting value from 1000
$table->id()->from(1000); // increment value start from 1000

->nullable(true) // boolean value

->default(your value);

//We can apply unique()

$table->string('slug')->unique();

or
$table->string('slug');
$table->->unique('slug');

//if you want to apply multiple unique, you can do it using array
$table->unique(['slug','your_column_name']);

//if you want apply uniqueness on two columns or more 
$table->unique(['columnName1', 'columnName2']);

//Creating UUID:
 $table->uuid('user_id')->primary();

//Creating relationship with uuid (relation another table)
$table->uuid('user_id')->primary();
$table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');

//To setup default DB timestamp
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

//To Insert some data by default
    public function up()
    {
        Schema::create('roles_modules', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 250)->default(''); 
            $table->integer('fixed_id')->unique()->default(0); 
            $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
        });

        $data = array(
            array(
                'name' => 'User',
                'fixed_id' => 101                              
            ),
            array(
                'name' => 'Candidates',
                'fixed_id' => 102
            ),
            array(
                'name' => 'Job Orders',
                'fixed_id' => 103
            ),
            array(
                'name' => 'Companies',
                'fixed_id' => 104
            ),
            array(
                'name' => 'Reports',
                'fixed_id' => 105
            ),
            array(
                'name' => 'Settings',
                'fixed_id' => 106
            ),
            array(
                'name' => 'Dashboard',
                'fixed_id' => 107
            ),
            array(
                'name' => 'Skills',
                'fixed_id' => 108
            ),
            array(
                'name' => 'Clients',
                'fixed_id' => 109
            ),
        );
        DB::table('roles_modules')->insert($data);
    }

###
###
######
Laravel has seeder feature, To insert some master data in database while migrating. 

php artisan make:seeder UserSeeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $users = [
            [
                'user_id' => '4bace869-9bc0-424c-9292-111dac5b7ee7',
                'first_name' => 'Admin',
                'middle_name' => 'D',
                'last_name' => 'Doe',
                'email' => 'admin@mailinator.com',
                'password' => Hash::make('India@123'),
                'role_id' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'user_id' => Str::uuid(),
                'first_name' => 'Jane',
                'middle_name' => 'E',
                'last_name' => 'Smith',
                'email' => 'sid@mailinator.com',
                'password' => Hash::make('India@123'),
                'role_id' => 2,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'user_id' => Str::uuid(),
                'first_name' => 'Alice',
                'middle_name' => 'F',
                'last_name' => 'Johnson',
                'email' => 'alice.johnson@example.com',
                'password' => Hash::make('password'),
                'role_id' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            // Add more users as needed
        ];

        // Insert users and create profiles
        foreach ($users as $user) {
            DB::table('users')->insert($user);

            $profileData = [
                'user_id' => $user['user_id'],
                'kyc_status' => 'Pending',
                'dob' => Carbon::now()->format('Y-m-d'), // Adjust as needed
                'account_type' => $user['role_id'] === 1 ? 'Corporate' : ($user['role_id'] === 2 ? 'Personal' : 'Personal'),
                'sex' => 'Male', // Adjust as needed
                'phone_no' => '1234567890', // Adjust as needed
                'country_id' => 1, // Adjust as needed
            ];

            if ($profileData['account_type'] === 'Corporate') {
                $profileData['company'] = 'Example Corp';
                $profileData['company_sector'] = 'Technology';
                $profileData['company_address'] = '1234 Example St';
            }

            DB::table('profiles')->insert($profileData);
        }
    }
}



After this you need to update userSeeder on databaseSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();

        // User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);

        // Call the UserSeeder
        $this->call(UserSeeder::class);       
    }
}


and then finally run migrate

php artisan migrate:fresh --seed


Comments

Popular posts from this blog

Laravel form validations

 Laravel Validations: List of types "first_name" => 'required|alpha:ascii|min:3|max:100',// alpha:ascii (only accepts a-z) "middle_name" => 'string', "last_name" => 'required|string', "email" => 'required|email|unique:users,email', "password" => 'required|string|confirmed', "sex" => 'required|string', "phone_no" => 'required|string', "account_type" => 'required|string', "dob" => 'required|date_format:d-m-Y', // date with format "nationality" => 'required|string', "company" => 'required|string', "company_sector" => 'required|string', "company_address" => 'required|string' "bank_account_no" => 'required|min_digits:3|max_digits:5', "role" => 'required|in:admin,editor,viewer', ...

React Js Commands

React JS Commands and Useful purposes  To Install react app: npx create-react-app app-name To Install react app: npx create-react-app . To check npm version: npm --version Inside that directory, you can run several commands:   npm start     Starts the development server.   npm run build     Bundles the app into static files for production.   npm test     Starts the test runner.   npm run eject     Removes this tool and copies build dependencies, configuration files     and scripts into the app directory. If you do this, you can’t go back! node -v (To check node version) The latest recommended command to create a new React app is: npx create-react-app@latest my-app Replace my-app with your desired project name. This approach uses the latest version of Create React App and works if Node.js (version 14+) and npm (version 5.2+) are installed Modern Alternatives If you prefer a faster, lighter setup, many developers n...

AngularJS - Directives

First, we have to learn AngularJs directives, Directives are simple special attributes in HTML. It has own set of built-in directives which offers functionality to your applications. To check all directive list https://docs.angularjs.org/api/ng/directive  For example, I take ng-app , ng-model ,  ng-init and ng-bind .  First will talk about the ng-app directive, the ng-app directive is initializing the AngularJS application. To take the values of all HTML inputs ( input, radio, select and textarea ) we use the ng-model.     ng-bind is print the expression. we can also be written inside double braces: {{ expression }} . AngularJS - Directives Example 1  Note: All these directives are work in inside the ng-app closed tag. you can assign ng-app directive to any tag. like <HTML>, <DIV>, <SPAN> but make sure initialize the main parent tag.     Now, We can check data initializes before page load. For this, ...