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

Reactjs jsx

ReactJS JSX   React is a modular, scalable, flexible, and popular front-end framework. What is JSX? JSX is a syntax extension for JavaScript. It was written to be used with React. JSX code looks a lot like HTML. What does “syntax extension” mean? In this case, it means that JSX is not valid JavaScript. Web browsers can’t read it! If a JavaScript file contains JSX code, then that file will have to be compiled. This means that before the file reaches a web browser, a JSX compiler will translate any JSX into regular JavaScript. Codecademy’s servers already have a JSX compiler installed, so you don’t have to worry about that for now. Eventually we’ll walk through how to set up a JSX compiler on your personal computer. JSX is a syntax extension for JavaScript which allows us to treat HTML as expressions. const h1 = <h1>Hello world</h1>; They can be stored in variables, objects, arrays, and more! Here’s an example of several JSX elements being stored in an object: const ...