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

Data Types in Python

Data Types  In C# or Java, You need to declare a variable specify them integer, string, and decimal. But in Python no need to specify. We can declare variables like Example: C# or Java int age = 28; string Name = "Siddhu"; Example: Python age = 28 Name = "Siddhu" So, you don't need to declare variable types in python. This is an advantage in Python, But still have few Disadvantages too. Example: In my Python function def add_numbers(x,y): print(x+y) add_numbers(20,50) //Output: 70 add_numbers(20,"Something") //Error:"Traceback (most recent call last): File "C:/Users/siddhartha.e/PycharmProjects/siddhu-py/my1stpycode.py", line 8, in add_numbers(50,"Something") File "C:/Users/siddhartha.e/PycharmProjects/siddhu-py/my1stpycode.py", line 4, in add_numbers print(a + b) TypeError: unsupported operand type(s) for +: 'int' and 'str'" ...

Database and Migrations

Database and Migrations You can config Database in the .env file. By default, Laravel has MySQL configuration. For example, I configured my details DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Laravel_tutorials DB_USERNAME=root DB_PASSWORD= So how it connects the database, In your root folder config/database.php file will read the .env file configuration. Migrations: Migrations are most likely a version control for your database. Advantages You can easily allow your team to modify database schema and share to everyone in the application No headache to add a new column in the database manually. This migration will help all teammates into one path. Now check with artisan command php artisan migrate php artisan migrate This command will create basic users,password_resets and migrations tables. Here migrations table will track of all migrates You can undo previous migration using rollback command php artisan ...

How to see Competitor ads on their Facebook pages

In any type of business, the organization always concentrate on their competitor's activities when it comes to competition. The first thing wants to what competitors doing, how they are getting leads or traffic. The same pattern is going when you are running Facebook Ads. If you want to know your competitor facebook strategy you will not see them on the newsfeed. Fortunately, you can see them in the following way and replicate their success on your Facebook Ads. Here am giving step by step. Follow each step  Step 1: Open your competitor facebook page and see the right side content of the page and click on see more button of the page transparency section as per below image Step 2: After opening the page you can see the page history and  Ads from this page. Click on Go to Ad library.  Step 3: Select the country that you want to see the Ads and see the Ads monthly.