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 Commands

Laravale commands #Check route list php artisan route:list #Check upload files links php artisan storage:link #Check database connected or not php artisan db #Make Request file php artisan make:request YourNameRequest #Make Controller #(In this statement you used -r -> resources and -m -> model. It will create CustomersController and Customers Model files) php artisan make:controller CustomersController -r -m Customers #Make Resource file php artisan make:resource CustomersResource #To check migration files status that those files are running or not with below commands php artisan migrate:status #To check if there is any pending migrate files to run #(also this command shows us the mysql query before running migration file) php artisan migrate --pretend #To make a database table (in this example Products name as taken) php artisan make:migration create_products_table #To create a Request file php artisan make:request StoreProductRequest php artisan make:request Up...

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