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)

What is AngularJS?

AngularJs is nothing but an MVC style javascript framework for creating single page apps. It is a javascript framework or we can say  "A framework will build client applications in HTML, CSS and Javascript/Typescript" This should be added within HTML  <script> tag. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script> Angular Js mainly used to make a single page, data-driven application. As well as we can add additional content brought into the web page without the need to refresh. Before going to AngularJS, We should know the     HTML     CSS     JavaScript     Json (optional)  Benefits of using angular Js     Gives our applications a clean structure     Includes a lot of re-usable code     Makes our applications more testable      Using Angular makes your life easier!   Let's Start learning with ...