InfyOm Blog

latest-post

Nowadays multi-tenant applications are more useful than single-tenant applications. We can use multi-tenant with multiple databases or single databases as per our need. But it's better to use a single DB with a multi-tenant when you have a small application.

In this tutorial, we are going to use multi-tenant with a single database.

We will implement multi-tenant with single DB by using the following package: https://github.com/archtechx/tenancy

Assuming you already have Laravel 8 repo setup. Now please follow the given steps to implement multi-tenancy with a single DB.

Package Installation

Run following commands :

  1. composer require stancl/tenancy

  2. php artisan tenancy:install

  3. php artisan migrate

Add following service provider to config/app.php

App\Providers\TenancyServiceProvider::class

Create Custom Model

Now create modal named MultiTenant into app\Models

MultiTenant.php

 SavingTenant::class,
        'saved'    => TenantSaved::class,
        'creating' => CreatingTenant::class,
        //        'created' => TenantCreated::class,
        'updating' => UpdatingTenant::class,
        'updated'  => TenantUpdated::class,
        'deleting' => DeletingTenant::class,
        'deleted'  => TenantDeleted::class,
    ];
}

Update Tenancy Configuration

As we have added custom model we also need to define that model into config/tenancy.php

Please change tenant_model value to our custom model.

'tenant_model' => \App\Models\MultiTenant::class,

Add Resolver

To use multi tenant with single DB we also need to add our customer resolver, that will be used into Middlewares that we will create ahead.

Create MultiTenantResolver into app\Resolvers

App\Resolvers\MultiTenantResolver.php

find(Auth::user()->tenant_id)) {
            return $tenant;
        }

        throw new TenantCouldNotBeIdentifiedByPathException($id);
    }

    public function getArgsForTenant(Tenant $tenant): array
    {
        return [
            [$tenant->id],
        ];
    }
}

Add Middleware

We will create our custom middleware that will set the current tenant into cache, and that will used by package to fire default query where('tenant_id', "tenant id we have set into middleware")

App\Http\Middleware\MultiTenantMiddleware.php

tenancy = $tenancy;
        $this->resolver = $resolver;
    }

    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $tenant = Auth::user()->tenant_id;

        return $this->initializeTenancy(
            $request, $next, $tenant
        );
    }
}

Also, don't forget to add middleware alias into App\Http\kernel.php

 protected $routeMiddleware = [
        ..............
        'multi_tenant' => MultiTenantMiddleware::class,
];

Now we will apply this multi_tenant middleware to our routes.

Add Trait to tenant-specific models

We have to add BelongsToTenant trait to all of our tenant-specific models.

Say if we want to add tenant_id into the users table then we must have to add BelongsToTenant to the app\Models\User model.

That trait will by default add following query everytime when we will try to fetch records or update records.

Where('tenant_id', 'tenant id will taken from cache')

Add tenant_id to tenant-specific migrations

As we have added the tenant trait, we must have to add tenant_id into tenant-specific migrations as specified below.

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            ...........................

            $table->string('tenant_id');

            $table->foreign('tenant_id')
                ->references('id')
                ->on('tenants')
                ->onUpdate('cascade')
                ->onDelete('cascade');

            $table->timestamps();
        });

Update TenancyServiceProvider

Replace the App\Providers\TenactServiceProvider by the following code.

 [],
            Events\TenantCreated::class => [
                JobPipeline::make([
                    Jobs\CreateDatabase::class,
                    Jobs\MigrateDatabase::class,
                    // Jobs\SeedDatabase::class,

                    // Your own jobs to prepare the tenant.
                    // Provision API keys, create S3 buckets, anything you want!

                ])->send(function (Events\TenantCreated $event) {
                    return $event->tenant;
                })->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production.
            ],
            Events\SavingTenant::class => [],
            Events\TenantSaved::class => [],
            Events\UpdatingTenant::class => [],
            Events\TenantUpdated::class => [],
            Events\DeletingTenant::class => [],
            Events\TenantDeleted::class => [
                JobPipeline::make([
                    Jobs\DeleteDatabase::class,
                ])->send(function (Events\TenantDeleted $event) {
                    return $event->tenant;
                })->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production.
            ],

            // Domain events
            Events\CreatingDomain::class => [],
            Events\DomainCreated::class => [],
            Events\SavingDomain::class => [],
            Events\DomainSaved::class => [],
            Events\UpdatingDomain::class => [],
            Events\DomainUpdated::class => [],
            Events\DeletingDomain::class => [],
            Events\DomainDeleted::class => [],

            // Database events
            Events\DatabaseCreated::class => [],
            Events\DatabaseMigrated::class => [],
            Events\DatabaseSeeded::class => [],
            Events\DatabaseRolledBack::class => [],
            Events\DatabaseDeleted::class => [],

            // Tenancy events
            Events\InitializingTenancy::class => [],
            Events\TenancyInitialized::class => [
//                Listeners\BootstrapTenancy::class,
            ],

            Events\EndingTenancy::class => [],
            Events\TenancyEnded::class => [
                Listeners\RevertToCentralContext::class,
            ],

            Events\BootstrappingTenancy::class => [],
            Events\TenancyBootstrapped::class => [],
            Events\RevertingToCentralContext::class => [],
            Events\RevertedToCentralContext::class => [],

            // Resource syncing
            Events\SyncedResourceSaved::class => [
                Listeners\UpdateSyncedResource::class,
            ],

            // Fired only when a synced resource is changed in a different DB than the origin DB (to avoid infinite loops)
            Events\SyncedResourceChangedInForeignDatabase::class => [],
        ];
    }

    public function register()
    {
        //
    }

    public function boot()
    {
        $this->bootEvents();
//        $this->mapRoutes();

        $this->makeTenancyMiddlewareHighestPriority();
    }

    protected function bootEvents()
    {
        foreach ($this->events() as $event => $listeners) {
            foreach (array_unique($listeners) as $listener) {
                if ($listener instanceof JobPipeline) {
                    $listener = $listener->toListener();
                }

                Event::listen($event, $listener);
            }
        }
    }

    protected function mapRoutes()
    {
        if (file_exists(base_path('routes/tenant.php'))) {
            Route::namespace(static::$controllerNamespace)
                ->group(base_path('routes/tenant.php'));
        }
    }

    protected function makeTenancyMiddlewareHighestPriority()
    {
        $tenancyMiddleware = [
            // Even higher priority than the initialization middleware
            Middleware\PreventAccessFromCentralDomains::class,

            Middleware\InitializeTenancyByDomain::class,
            Middleware\InitializeTenancyBySubdomain::class,
            Middleware\InitializeTenancyByDomainOrSubdomain::class,
            Middleware\InitializeTenancyByPath::class,
            Middleware\InitializeTenancyByRequestData::class,
        ];

        foreach (array_reverse($tenancyMiddleware) as $middleware) {
            $this->app[\Illuminate\Contracts\Http\Kernel::class]->prependToMiddlewarePriority($middleware);
        }
    }
}

Create / Fetch Tenant

Now we have to create a tenant and give that tenant_id to related users.

each user contains their specific tenant_id.

Use the following code to create a tenant :

 $tenant1 = \App\Models\MultiTenant::create([
     'name' => 'Tenant 1'
 ]);

 $tenant2 = \App\Models\MultiTenant::create([
     'name' => 'Tenant 2'
  ]);

That will create tenant into tenants table and values will be stored into data column as a son.

$tenant1 = App\Models\MultiTenant::where('data->name', 'Tenant 1')->first();

$tenant2 = App\Models\MultiTenant::where('data->name', 'Tenant 2')->first();

$tenant1User = User::where('id', 'user id here')->update(['tenant_id' => $tenant1->id]);

$tenant2User = User::where('id', 'user id here')->update(['tenant_id' => $tenant2->id]);

Now we have 2 tenants with 2 separate users who contain separate tenant ids.

Add Middleware to Routes

Now do login with User 1 and try to fetch all users from the database, it will return users of logged-in users' tenants only.

As we have the BelongToTenant trait into the User model.

Route::group(['middleware' => ['auth', 'multi_tenant']], function () { Route::get('users', function() {

 // only tenant-1 users will be returned because we are setting the logged-in user tenant into the cache from `multi_tenant`middleware.
 $allUsers = User::all();
});

});

You can use the same for other models too.

Hope this helps you.

August 14, 20212 minutesuserVishal Ribdiya

Posts

post
post

Lots of people ask me frequently, "Which are the laravel packages that you use in almost all projects?" when we meet in Meetup or any other events regardless of its online or physical events.

Let me describe today some of the packages that we almost use in all of the projects.

We have been working in Laravel for almost 7+ years and in these years we have used lots of packages, some from the community and some of our own.

I am categorizing these into 2 categories.

  1. Most used packages
  2. Common Need/Functionality specific packages

Most used packages

These are the packages which must be included in all of our projects. No Excuses.

barryvdh/laravel-ide-helper

Laravel exposes a lot of magic methods and properties. IDE Helper is a very good package when it comes to auto-complete those properties and methods. Even it does an amazing job while refactoring properties or methods of the model.

barryvdh/laravel-debugbar

The second one is from the same author, debugbar helps to debug the request in terms of the number of queries fired, time taken by each query, number models retrieved from db, time taken by each request, and much more.

imanghafoori/laravel-microscope

Laravel Microscope improves the readability of your code. Early returns, unnecessary else statements, and many more. so your code looks clean and efficient in terms of execution as well.

beyondcode/laravel-query-detector

One of the problems that we face is, missing eager loading. In ongoing development, sometimes we add relationships objects in the loops, and then laravel fires tons of queries to the database. Laravel Query Detector detects that and gives a warning while developing the environment.

InfyOmLabs/laravel-generator

No application can be ever built without a few CRUDs. CRUDs are essential in almost all web applications. Also, APIs of CRUDs are essential while building a backend for Mobile or Frontend apps. Laravel Generator is our own developed package that we use in all of the applications to make the CRUD building process faster. It can be used with two themes right now, AdminLTE and CoreUI. But it's also frontend framework agnostic.

Common Need/Functionality specific packages

These are the packages that are used when we particularly need that kind of functionality in the application.

Will keep this list updating.

September 11, 20202 minutesauthorMitul Golakiya
post

Step 1: Selection of your Subject

select any selection tool for selection but select the Quick selection tool.

select your subject and press select and mask setting

2020-12-11_5fd30647f2a82

Step 2: Edit your Subject

  1. Open property and select onion skin and transparency 50%
  2. Refine edge brush tool and then refine edge
  3. Set contrasts 9%
  4. Output setting on
  5. Tick decontaminate colors amount 100%
  6. Output to a new layer with layer mask then press OK

2020-12-11_5fd307135f8ec

Step 3: Crop the Upper part of the subject

Select layer mask and press ctrl + click for selection and new cut out the upper part to polygonal lasso tool. select perfectly then select layer and ctrl+j for duplicate layer

2020-12-11_5fd30764bf1fc

Step 4: Create an effect for Background

Create Ctrl+G for the group layer, select the last layer and create a color lookup effect.

Then 3D lut file and select moonlight.3dl. and then Create a new effect black & white Opacity set 50%

2020-12-11_5fd309224b0ce

Step 5: Create Effect for Main Subject

Select the group layer and convert this layer to a Smart Object.

Then create this layer duplicate. then create a color style to the top layer in linear Dodge(Add).

Then go to the

2020-12-11_5fd309f0a9d2c

  1. Filter - blur - Gaussian blur Create radius - 5 for soft edges
  2. Create a duplicate layer and double click on the smart filter and Create a radius of 100

2020-12-11_5fd30a00d1eea

  1. again Create a duplicate layer and double click on the smart filter and Create a radius of 2504. again Create a duplicate layer and double click on the smart filter and Create a radius of 500 then add hue/saturation adjustment layer and click on create clipping mask then click on colorize and increase the saturation to your perfect and choose a color

2020-12-11_5fd30a6250351

Step 6: Create All effects in the subject

Select the main layer mask image and create effect curves.

And click on create effect curves and click on create clipping mask and curves per requirement select layer mask and select the brush tool. and set property opacity 100%flow 30%

2020-12-11_5fd30ab6dfb02

Create a duplicate hue/saturation effect layer and set this layer to the bottom of the main object and select this layer and open property and click ok create a clipping mask.

And select the mask and make sure the foreground color is white.

And give shade to the object and you can also adjust the opacity.

Step 7: Add the sparkle and give effect

Let's add sparkle and change the blending yo screen.

2020-12-11_5fd30b69e1b01

Then add a mask and convert to invert the layer and select brush tool.set foreground color is white and creates an effect in the main object after creating effect open blending mode and create a level and click on create a clipping mask and set property per requirement.

Then open blending mode and select color lookup and set 3dlutfile to crisp_warm: look and set opacity as per requirement.

Now finally ready to glow effect

2020-12-11_5fd30bbe60c28

September 10, 20202 minutesauthorKishan Savaliya
post

Introduction

You can only develop products and services that are very effective if you pay attention to the needs of your customers and prospects. One way to understand exactly what your customers want is through research and surveys.

1. Understand your customers

You can only develop products and services that will be a big hit if you pay attention to the needs of your customers and prospects. One way to understand exactly what your customers want is through research and surveys. You should constantly invite them to give honest, brutal feedback.

Reviews and surveys are the best way to get into the minds of your customers. This makes it easier for you to develop products and services that are appropriate to the current demands of the market. Moreover, it helps you understand the area in which your company needs to improve.

2. Improving customer service

If you do not provide quality customer service, it will be difficult to satisfy your customers even if you have an excellent product or service. This aspect of the business is about taking extra steps to make them feel special. Let your customers know that they have value. If they have a problem, make sure you address them immediately. If they have questions, take the time to answer.

They should not feel that things are difficult for them if they raise specific issues. Social media is the best way to listen to and understand your customers. If they find customer service satisfactory, they may also recommend buying others from your business.

3. Establish loyalty

It takes time to encourage customers to come and buy what you offer. But just buying them is not enough. You need to promote loyalty. Considering there are other competitors who can offer them better, you want them to stay loyal to you. Don’t be satisfied just because you already have a lot of loyal customers.

They can easily be attracted to other options and they can leave you. Provide loyalty rewards. If there are discounts and discounts, let these most loyal customers be the first to know. You must make sure your customers know they are appreciated.

4. Focus on professional development

The success of your business also depends on the quality of the employees you hire. Building an effective team is the key to making sure your business grows.

One of the best ways to motivate hardworking employees is to give them a sense of purpose. They should not feel that they have to work just to work.

5. Understand your customers

Find ways to increase the sales of your existing customers. It's much cheaper than finding a new one. Even if you can't expand your product line, you can still sell more of your existing product or service to a client you already have. An easy way to do this is by volume discount.

6. Participate in networking events

Take the time to build your networks - it's not what you know but who you know. Networking allows you to build relationships with other people and encourage customers to refer to you through words.

7. Give back to your community

Creating brand awareness in your local community is a great way to attract new business. Consider participating in a sponsorship or community event to enhance your business profile.

We will see more points in our next tutorial.

September 07, 20203 minutesauthorAnkit Kalathiya
post

Most of the developers are facing a select2 style removing issue when livewire renders the component.

We can resolve this issue by using a livewire javascript hook.

Here is my screen with select2 before livewire component rendering.

2020-12-10_5fd2207b2f583

And when the livewire component is refreshed means re-render the select2 style is gone ☹️

2020-12-10_5fd221ec084b8

How to Fix it ?? 🤔

Well, you just need to add some JQuery code to your livewire component. Here we are going to use afterDomUpdate webhook of livewire. add the following code to your livewire component :

document.addEventListener('livewire:load', function (event) {
   window.livewire.hook('afterDomUpdate', () => {         
   $('#select2ID').select2();     
   }); 
});

livewire:load is listening events when the livewire component is loaded and we can add our code within it.

And now when your livewire component is refreshed your select2 style will be still there as we are again applying it.

Other Livewire Posts:

Stay tuned to us for more interesting stuff about livewire.

September 03, 20201 minuteauthorVishal Ribdiya
post

Software Testing Life Cycle (STLC) identifies the test activities to perform and when to perform those test activities. While testing differs between organizations, there is a test lifecycle.

There are mainly eight phases of STLC

  1. Requirement Analysis
  2. Test Planning And Control
  3. Test Analysis
  4. Test Case Development
  5. Test Environment Setup
  6. Test Execution
  7. Exit Criteria Evaluation And Reporting
  8. Test Closure

2020-12-10_5fd21d73795c8

Requirement Analysis:-

The entry criteria for this phase is the BRS document (Business Requirements Specification). During this phase, the test team studies and analyzes the requirements from a test perspective.

This phase helps to identify whether the requirements are likely or not. If any requirement is not verifiable, the test team can communicate with various stakeholders (customer, business analyst, technical leaders, system architects, etc.) during this phase so that the mitigation strategy can be planned.

Entry criteria: BRS (Business Requirement Specification) Results

Deliverables: list of all verifiable requirements, automation feasibility report (if applicable)

Test Planning And Control:-

Test planning is the first step in the testing process. At this stage typically Test Manager Test Lead involves determining the effort and cost estimates for the entire project. The preparation of the Test Plan will be made on the basis of the requirements analysis. Activities such as resource planning, determination of roles and responsibilities, selection of tools (if automation), training requirements, etc., are carried out at this stage.

The deliverables of this phase are Test Plan & Effort estimation documents.

Entry Criteria: Requirements Documents

Deliverables: Test Strategy, Test Plan, and Test Effort estimation document.

Test Analysis:-

Test Analysis Is the process of analyzing the test basis (all documents from which the requirements of a component or system can be inferred) and defining test objectives. It covers WHAT is to be tested in the form of test conditions and can start as soon as the basis for testing is established for each test level.

Following Is The Document Which Is Use In Test Analysis:-

  • CRS (Customer Requirement Specification)
  • SRS (Software Requirement Specification)
  • BRS (Business Requirement Specification)
  • Functional Design Documents

Test Case Development:-

This phase begins after the test planning and analysis phase is completed. From test analysis, we can understand how to test and what the test condition is. So easily understand and develop the test case. In This phase, the evaluator creates the manual / automation test scripts. The test data is prepared in this phase and the data is used to find the defect. The Requirement Traceability Matrix (RTM) is also ready Because the evaluator understands tracking the test case for the particular requirement.

2020-12-10_5fd21d8345df1

Activities in the Test Case Development Phase

Following are the three activities that are carried out in the Test Case Development phase

Test Scenarios Identification

  1. Scenarios ease the testing and evaluation of a complex system. The following strategies help in creating good scenarios −
  2. Enumerate potential users, their actions, and their goals.
  3. Evaluate Users who have a hacker mindset and listed possible scenarios for abuse of the system.
  4. List System events and how the system handles these requests.
  5. List Benefits and create comprehensive tasks to verify.
  6. Read about similar systems and their behavior.
  7. Studying Complaints about competitors' products and their predecessors.

Test Cases Writing

A test case is a document, which includes test data, preconditions, expected results, and postconditions, developed for a particular test case in order to verify compliance with a specific requirement.

Test Case serves as a starting point for running the test. After a set of input, values ​​are applied; the application is final and leaves the system at an endpoint also known as a post-execution condition.

Test Data Preparation

Test Data is used to run the tests for test ware. Test Data must be precise and complete in order to detect the shortcomings. To achieve these three goals, follow a step-by-step approach as given below -

  1. Identify resources or test requirements
  2. Identify conditions/functionality to be tested
  3. Set priority test conditions
  4. Select conditions to test
  5. Determine the expected result of test case processing
  6. Create Test cases
  7. Document test
  8. conditions Conduct test
  9. Verify and correct test cases based on modifications

Activity Block Diagram

The following diagram shows the different activities that form part of Test Case Development.

2020-12-10_5fd21d921ebbe

Test Environment Setup:-

A test environment is a software and hardware configuration that allows test teams to run test cases. In other words, it supports running tests with configured hardware, software, and network. The testbed or environment is configured as needed Application Under Test. On some occasions, the test may be the combination of the test environment and the test data that it operates. Setting a good test environment guarantees successful software testing. Any Loopholes in this process can result in additional costs and time for the customer.

Process of Software Test environment setup

Tests are limited to what can be tested and what not should be tested.

Following people are involved in test environment setup

  • System Admins,
  • Developers
  • Testers
  • Sometimes users or techies with an affinity for testing.

The test environment requires setting up of a various number of distinct areas like,

Setup of Test Server

Test Every may not be performed on a local machine. It may need to create a test server that can support applications.

For example, Fedora configuration for PHP, Java-based applications with or without mail server, cron configuration, Java-based applications, and so on.

Network

Network set up as per the test requirement. It includes,

  • Internet setup
  • LAN Wi-Fi setup
  • Private network setup

It ensures that the congestion that occurs during testing doesn't affect other members. (Developers, designers, content writers, etc.)

Test PC setup

For web testing, you may need to set up different browsers for different testers. For desktop applications, you need various types of OS for different testers' PCs.

For example, Windows phone app testing may require.

  • Visual Studio installation
  • Windows phone emulator
  • Alternatively, assigning a Windows phone to the tester.

Bug Reporting

Bug reporting tools should be provided to testers.

Creating Test Data for the Test Environment

Many companies use a separate test environment to test the software product. The common approach used is to copy production data to test. This helps the tester to detect the same issues as a live production server, without corrupting the production data.

The approach for copying production data to test data includes,

  • Set up production jobs to copy the data to a common test environment
  • All PII (Personally Identifiable Information) is modified along with other sensitive data. The PII is replaced with logically correct, but non-personal data.
  • Remove data that is irrelevant to your test.

Testers or developers can copy this to their individual test environments. They can modify it as per their requirement.

Privacy is the main issue in copy production data. To overcome privacy issues you should look into obfuscated and anonymized test data.

For Anonymization of data two approaches can be used,

  • Blacklist: In this approach, all the data fields are left unchanged. Except those fields specified by the users.
  • Whitelist: By default, this approach, anonymizes all data fields. Except for a list of fields that are allowed to be copied. A whitelisted field implies that it is okay to copy the data as it is and anonymization is not required.

Also, if you are using production data, you need to be smart about how to source data. Querying the database using SQL script is an effective approach.

Every test may not be executed on a local machine. It may need establishing a test server, which can support applications.

For example, Fedora set up for PHP, Java-based applications with or without mail servers, cron set up, Java-based applications, etc.

Network

Network set up as per the test requirement. It includes,

  • Internet setup
  • LAN Wi-Fi setup
  • Private network setup

It ensures that the congestion that occurs during testing doesn't affect other members. (Developers, designers, content writers, etc.)

Test Execution:-

After The test plan, the development of the test case, and the configuration of the test environment are complete, and then the execution phase of the test is executed.

This manual test/automation script phase is executed. If any defect is detected during the execution of the test case, it will be reported to the developer through the bug tracking system.

If any test case result is a failure then this particular test case is marked as a failure.

If any test case result is matched to the expected result then a particular test case is marked as Pass.

If all module dependencies are tested and any fault is detected, the particular module test case is marked as blocked, first corrects the main module fault, and then runs the associated module test case. For example, B depends on module A.

If any fault is found in module A, the test case of module B is not executed. First correct the fault of module A then rerun the module A test case, If module A the result of the test case is Pass then run the module B execution of the test case.

Blocked Test noticed cases are executed after the fault is corrected by the developer.

2020-12-10_5fd21da3e8622

Exit Criteria Evaluation And Reporting:-

In this phase, if the exit criteria match the test result. In Termination Criteria, There is one condition that is predefined. At this stage, The test summary report is generated. A Document containing a summary of testing activities and final test results is called Test Summary Report.

Test Closure:-

In the final stage where we prepare the Test Closure Report, Test Metrics.

The testing team will be called out for a meeting to evaluate cycle completion criteria based on Test coverage, Quality, Time, Cost, Software, Business objectives.

The test team analyses the test artifacts (such as Test cases, defect reports, etc.,) to identify strategies that have to be implemented in the future, which will help to remove process bottlenecks in the upcoming projects.

Test metrics and Test closure reports will be prepared based on the above criteria.

Entry Criteria: Test Case Execution report (make sure there are no high severity defects opened), Defect report

Deliverables: Test Closure report, Test metrics

August 31, 20208 minutesauthorBhumi Khimani
post

Recently, we were working on a laravel app where we have a status column in multiple models. We have multiple processes going on for which we have different jobs.

Initially job status will be "Pending", then each job will take one record, change the status to "Running" and process that record, and update the status to either "Completed" or "Failed".

We have constants for each status. Something like below,

static $STATUS_PENDING = 0; static $STATUS_RUNNING = 1; static $STATUS_COMPLETED = 2; static $STATUS_FAILED = 3;

And the problem is, we need to go and define the status in every model that we have (around 10+ models).

Then we have functions to update status and check the status in each model like,

public function markRunning($saveRecord = true) {     $this->status = static::$STATUS_RUNNING;
    if ($saveRecord) {
        $this->save();
    }
}
 
public function isRunning()
{
    return $this->status === static::$STATUS_RUNNING;
}

And above functions existed for each 4 status. So what we did is, we created a common StatusTrait which can be used across multiple models.

Here is the code of StatusTrait that you can find for that.

Then in each model, we use this trait. For e.g.,

class SavePdf extends Model {     use StatusTrait;
    .....
}

And then can use any method of trait in all the models,

... $savePdf = new SavePdf(); $savePdf->markRunning(); ...

Or we can check if the status of the model is running or not. For e.g.,

... if ($savePdf->isRunning()) {     // logic here } ...

This is how we have saved tons of writing code and optimized the code. Another advantage is, we can just update the value of any status from one single place.

You can also check this kind of pattern and do something like this.

August 26, 20201 minuteauthorMitul Golakiya
post

After doing all the right things to boost productivity and still employees' productivity plunging or not increasing, we need to look at the Employee Morale. Employee Morale is a decisive factor in an Organisation whether it is the Service sector or Manufacturing unit. It is one of the cornerstones of the business, only a few organizations pay attention to morale among employees in their organization and this is the major mistake from their side as it affects productivity which ultimately reflects in Organizational Growth & Productivity.

Let’s Discuss:

  • What’s Employee Morale?
  • Characteristics of Employee Morale.
  • Relation between Morale & Productivity.

What is Employee Morale?

In simple terms employee morale is the standard of behavior of an employee which directly affects the productivity of the organization but it is a complex concept as there are ample factors that affect employee morale.

Definition:

Edwin Flippo: “ Morale is a mental condition or attitude of individual and groups which determines their willingness to cooperate”

Characteristics:

  • Psychological concept
  • Dynamic Nature
  • Group phenomenon
  • Reflect others

Psychological Concept:

Morale is a psychological phenomenon, it is the internal feeling of confidence, attitude, Zest, enthusiasm, satisfaction, etc. Moreover, it is the state of mind and emotions affecting the attitude and willingness to work that affect individual and organizational objectives.

Dynamic Nature:

Morale is Dynamic in nature; we cannot develop it overnight. Management has to make continuous efforts to build and maintain high morale among employees in the organization. It is a long-term concept.

Group Phenomenon:

Morale is not an individual phenomenon but it's the sum of the total employee’s attitude, feelings, and sentiments.

Reflect others:

We cannot measure morale directly but it is reflected in productivity, discipline, turnover, etc. To measure morale we need to look at other factors.

Relations between Morale and Productivity:

Davis Designed that there is not always a positive link between Productivity and Employee morale. There can be four combinations of Morale and Productivity

employee-morale-play-significant-role-in-business-development/1

1. High morale-High productivity

This situation is likely to occur when the employees are fully motivated to achieve high performance not only this but satisfied with all financial & nonfinancial rewards & highly satisfied with their job role. Feeling proud to be part of the organization/team.

2. High morale-low productivity

This situation occurs when the employees waste their time in the workplace or use the time to satisfy their personal goals. They don't care about organizational goals. There are many factors responsible for this kind of Employee Attitude in the workplace such as

  1. Lack of proper training,
  2. Lack of support by co-workers or leaders,
  3. Leaders/Superior behavior with him,
  4. Irresponsible Management (If we talk about It or another small service sector Irresponsible HR )
  5. Ineffective Supervision
  6. Restrictive norms of the informal group
  7. Outdated Technology & Methods

3.Low morale-High productivity

In a short period, it may be possible that with low morale Employee's productivity seems high but it is for a temporary or short span of time. Low Morale can not result in high productivity for a long time. this situation occurs when

  1. Fear of losing a job,
  2. Less availability of alternatives
  3. Strict Supervision, Rules & Regulations
  4. Punishment
  5. Policies and strategies focus on high productivity only.

4. Low morale-Low productivity

This situation occurs when the organizational & individual goals are not satisfied & other factors like

  1. Lack of motivation
  2. Unclear Job role
  3. Lack of harmonious Superior-Subordinate relationship

These all factors result in frustration, tension and grievances develop against managers which reflect low productivity. To pen down, morale is the paramount factor that gives a direct impact on productivity, Productivity impact on profitability, profitability impact on organizational growth. If the Morale is high then it will be possible to gain more fruits in the future but if it's low then it's Red Signal for any organization even the productivity is high but it will be for a short period of time only

I am not going to end the topic of Morale but will continue in the next blog with

  1. Factor determining morale
  2. Significance of high morale
  3. Impact of low morale
  4. Measurement of morale

To know about these please read my upcoming blogs of Human Resource…..

August 25, 20203 minutesauthorMariyam Bemat