Showing posts with label Laravel. Show all posts
Showing posts with label Laravel. Show all posts

Saturday, August 14, 2021

Integration of Queue in Laravel

Integration of Queue in Laravel

Introduction

Laravel Queue is to enhances the laravel application performance and provides a smooth process to do your heavy tasks without the hassle and waiting time.

For example like if you have Lacs of records and wanted to import them into the database in laravel you just implement the import feature and upload the CSV or excel file and import it but it will take mins or hours to import in the database and your application will stop working until all the records not imported in the database 

Laravel gives us a queue system that helps to run complex tasks in the background without stopping the application it just takes the time to execute the request not wait for the response and you will continue your work without waiting.

Configuration of Queue

Let’s take an example for a better understanding

Go to your laravel application folder and run the below command :

php artisan queue:table php artisan queue:failed-table

It will generate the below migrations for the queue-related tables.

Jobs table  : 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('queue')->index();
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
}
 

Failed Jobs Table : 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFailedJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('failed_jobs');
    }
}

Run the below command to migrate above migrations and generate tables

php artisan migrate

Once the migrate command is executed, you will find the “jobs” and “failed_jobs” tables in your database.

After the migration, the next step is to change the environment file .env to set the queue driver like below : 

QUEUE_CONNECTION = database 

Now need to create a queue job and for that need to run the below command 

php artisan make:job csvImport

You will get the job file in the folder app/Jobs named csvImport.php. The file has just 1 method handle() in it. 

The file contains below code : 

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class csvImport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
            
    }
}

You can add the logic to run through the job in the handle method

Now after setup the jobs you need to add them in the controller like below 

use App\Jobs\csvImport;

and in the controller method, you need to call the job through the below method to dispatch the job in the queue

It will add the job in the default queue : 

 csvImport::dispatch();

It will add the job in the default queue :

csvImport::dispatch()->onQueue('Customers');

We can use multiple queue names for multiple operations to differentiate it

After all the above steps just call your controller method and it will add your request to the queue and you can run the below command to execute all queues and there available jobs

For Example : 

php artisan queue:work –tries=5

“--tries” is used to defines the number of tries to run the job

Conclusion : 

Laravel queue is very easy to implement and use in your existing project, Also In case you feel that it is a daunting task to implement a laravel queue, you can reach me at “mp.inviable@gmail.com” to help you with the development process.





Friday, August 13, 2021

Integration of Supervisor in Laravel

Integration of Supervisor in Laravel


What is Supervisor in Laravel?


The supervisor is a process manager which Laravel suggests to use as a process monitor for queue workers. It will automatically start the queue worker in the background, even after the system has booted and will automatically restart the worker if the worker exits unexpectedly.
 
Why use it?

To automatically detect the jobs and process it as per the configuration. The supervisor is a client/server system that allows its users to monitor and control a number of processes.

How to use supervisor in Laravel?

Install supervisor by using the following command : 

sudo apt-get install supervisor 

After you have successfully installed supervisor, you will see a folder "supervisor" inside /etc/ with below mentioned file and folder.

supervisord.conf and conf.d folder 

If folder is not created, run this command: 

echo_supervisord_conf > /etc/supervisord.conf 

Now go to supervisor directory and run the command s below to add the configuration. 

touch laravel-worker.conf 

Now open laravel-worker.conf file and enter the configuration as per your requirements 

[program:laravel-worker] 
process_name=%(program_name)s_%(process_num)02d 
command=php <Laravel_Folder_Path>/artisan queue:work --tries=3 
autostart=true 
autorestart=true 
user=root 
numprocs=8 
redirect_stderr=true 
stdout_logfile=/var/log/supervisor/laravel-queue.log 

Save the file and scroll to the end of supervisord.conf in /etc/supervisor/supervisord.conf and change the path as mentioned below (if not available) 

files = /etc/supervisor/laravel-worker.conf 

 Now, Let's Start Supervisor to run the queue worker but before that lets check if supervisor is already running or not with the command below. 

 use ps -ef to check PID(process ID) and kill to finish the task. 

 Run : supervisord -c /etc/supervisor/supervisord.conf 

Run the following commands one by one after starting supervisor. 

sudo supervisorctl reread -- Restart all programs in configuration files 
sudo supervisorctl update -- Update configurations to supervisord 
sudo supervisorctl start laravel-worker:* -- Start a program 

 To check the status run the command: supervisorctl status

Sunday, September 13, 2020

Laravel JWT Authentication


Laravel JWT Authentication

To use JWT you must know about the below Features : 

Introduction

JWT is an authentication token by which we can easily transfer data between the third parties or for example when we use Laravel API we have secure our data through JWT Token. Generally, it is valid for 3600 sec. or 1 Hour. Most of the recent application development using it for API authentication for example Mobile, Web, Cloud, IoT for user identification, verification and information security. 

The Structure of JWT

JWT has 3 below parts : 

Header

    This is where JWT’s cookies are located. The standard is defined as follows.

    
        "alg": "HS256",
        "typ": "JWT"
    }

Alg: Where it determines the Cryptographic Algorithm for JWT. Supported Algorithms vary depending on the language you use. You can review supported Algorithms via jwt.io.

Typ: Indicates that the Header type used is JWT.

Payload

Although there are some standards here, it is the part that contains the data we want to carry in general. To mention some standard keys;

iss (issuer): Publisher
sub (subject): Subject
exp (expiration time): Expiration date
nbf (not before time): Before this Date
iat (issued at the time): Created on

Signature

This is the part where the Key is used to create the JWT. The header is encrypted with the specified encryption method.

~~~

Except for the signature part of the JWT you produce, the data can be read in it. Simply decode the Base64. But you cannot make any changes to the information in the content because the key will become unusable.


Let's have look how can we install and use it in our application


To install JWT we need to first install Tymon JWT Package using the composer to add it in Laravel

composer require tymon/jwt-auth

After installation is done need to publish its configuration

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Now run the below command to generate the secret key

php artisan jwt:secret

After the above command opens the file "config/auth.php" inside guards in API section add the driver as jwt to use it for all API requests.

'guards' => [
      'web' => [
          'driver' => 'session',
          'provider' => 'users',
      ],
      'api' => [
          'driver' => 'jwt',
          'provider' => 'users',
      ],
  ],
 
Now, our application will be using Laravel JWT tokens for all the API authentication.

Creating API to get Laravel JWT Authentication Token

The next step is to create a login route through which we will send Laravel JWT tokens to our users through which they will authenticate other APIs. Let’s generate a new API controller and create a login method in it. For this, you must create a function that will send a common response to all the users.

  function commonResponse($custom_message,$data,$errors = [],$status = true)
    {
        $result = [
            "message" => $custom_message,
            "status" => $status,
            "data" => $data,
            "errors" => $errors
        ];

        return response()->json($result, 200);
    }
  

After creating the function, it’s time to create our login method which will take email and password and will return a JWT token along with its expiry time.


public function login(Request $request)
  {
      $data = $request->all();
      $errors = [];
      $data = [];
      $message = "";
      $status = true;
      $validator = Validator::make($data,[
          'email' => 'required',
          'password' => 'required',
      ]);

      if ($validator->fails()) {           
          $status = false;
          $errors = $validator->errors();
          $message = "Something went wrong, Login Failed email or password missing";
      }

      $credentials = $request->only("email", "password");

      if (! $token = auth('api')->attempt($credentials)) {
          $status = false;
          $errors = [
              "login" => "Invalid username or password",
          ];
          $message = "Login Failed";
      }else{
          $message = "Login Successfull";
          $data = [
              'access_token' => $token,
              'token_type' => 'bearer',
              'expires_in' => auth('api')->factory()->getTTL() * 60
          ];
      }

      return $this->commonResponse($message,$data,$errors,$status);
  }

Next, we will update our previous login route in routes/api.php file with new login controller.

Route::post('login','LoginController@login');

These JWT tokens will now be used as a bearer token for all the API authentication processes.

Summary 

Laravel JWT provides a secure route to transfer data across platforms, as it comprises a header and end-to-end signature that ensures a fast and secure representation of data between two parties.

If you have some questions regarding this post or want to contribute more on this topic, feel free to give your suggestions below in the comments section.

Wednesday, September 9, 2020

Laravel 8 New Features

 Laravel 8 New Features

Laravel Jetstream

Laravel Jetstream is a beautifully designed application temporary structure for Laravel. Jetstream provides the main starting point for your next project and it includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management. Laravel Jetstream replaces and improves upon the legacy authentication UI scaffolding available for previous versions of Laravel.

Models Directory

Now you can access all your models from new directory that's app/Models, instead of app folder all commands also default assumes that they get all the models from app/Models.

Model Factory Classes


Eloquent model factories have been entirely re-written as class based factories and improved to have first-class relationship support. For example, the UserFactory included with Laravel is written like so:

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}
Thanks to the new HasFactory trait available on generated models, the model factory may be used like so:

use App\Models\User;

User::factory()->count(50)->create();

Since model factories are now simple PHP classes, state transformations may be written as class methods. In addition, you may add any other helper classes to your Eloquent model factory as needed.

For example, your User model might have a suspended state that modifies one of its default attribute values. You may define your state transformations using the base factory's state method. You may name your state method anything you like. After all, it's just a typical PHP method:

/**
 * Indicate that the user is suspended.
 *
 * @return \Illuminate\Database\Eloquent\Factories\Factory
 */
public function suspended()
{
    return $this->state([
        'account_status' => 'suspended',
    ]);
}
After defining the state transformation method, we may use it like so:
use App\Models\User;

User::factory()->count(5)->suspended()->create();

 As mentioned, Laravel 8's model factories contain first class support for relationships. So, assuming our User model has a posts relationship method, we may simply run the following code to generate a user with three posts:

$users = User::factory()
            ->hasPosts(3, [
                'published' => false,
            ])
            ->create();

Migration Squashing

As you build your application, you may accumulate more and more migrations over time. This can lead to your migration directory becoming bloated with potentially hundreds of migrations. If you would like, you may now "squash" your migrations into a single SQL file. To get started, execute the schema:dump command:

php artisan schema:dump

// Dump the current database schema and prune all existing migrations...
php artisan schema:dump --prune

 When you execute this command, Laravel will write a "schema" file to your database/schema directory. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will execute the schema file's SQL first. After executing the schema file's commands, Laravel will execute any remaining migrations that were not part of the schema dump.


Job Batching

Laravel's job batching feature allows you to easily execute a batch of jobs and then perform some action when the batch of jobs has completed executing.

The new batch method of the Bus facade may be used to dispatch a batch of jobs. Of course, batching is primarily useful when combined with completion callbacks. So, you may use the then, catch, and finally methods to define completion callbacks for the batch. Each of these callbacks will receive an Illuminate\Bus\Batch instance when they are invoked:
use App\Jobs\ProcessPodcast;
use App\Podcast;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Batch;
use Throwable;

$batch = Bus::batch([
    new ProcessPodcast(Podcast::find(1)),
    new ProcessPodcast(Podcast::find(2)),
    new ProcessPodcast(Podcast::find(3)),
    new ProcessPodcast(Podcast::find(4)),
    new ProcessPodcast(Podcast::find(5)),
])->then(function (Batch $batch) {
    // All jobs completed successfully...
})->catch(function (Batch $batch, Throwable $e) {
    // First batch job failure detected...
})->finally(function (Batch $batch) {
    // The batch has finished executing...
})->dispatch();

return $batch->id;

Improved Rate Limiting

Laravel's request rate limiter feature has been augmented with more flexibility and power, while still maintaining backwards compatibility with previous release's throttle middleware API.

Rate limiters are defined using the RateLimiter facade's for method. The for method accepts a rate limiter name and a Closure that returns the limit configuration that should apply to routes that are assigned this rate limiter:
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000);
});
Since rate limiter callbacks receive the incoming HTTP request instance, you may build the appropriate rate limit dynamically based on the incoming request or authenticated user:
RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100);
});

Sometimes you may wish to segment rate limits by some arbitrary value. For example, you may wish to allow users to access a given route 100 times per minute per IP address. To accomplish this, you may use the by method when building your rate limit:

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100)->by($request->ip());  });                    

 

Rate limiters may be attached to routes or route groups using the throttle middleware. The throttle middleware accepts the name of the rate limiter you wish to assign to the route:


Route::middleware(['throttle:uploads'])->group(function () {
    Route::post('/audio', function () {
        //
    });

    Route::post('/video', function () {
        //
    });
});

Closure Dispatch / Chain

Using the new catch method, you may now provide a Closure that should be executed if a queued Closure fails to complete successfully after exhausting all of your queue's configured retry attempts:

 

 use Throwable;

dispatch(function () use ($podcast) {
$podcast->publish(); })->catch(function (Throwable $e) { // This job has failed... });

Dynamic Blade Components

Sometimes you may need to render a component but not know which component should be rendered until runtime. In this situation, you may now use Laravel's built-in dynamic-component component to render the component based on a runtime value or variable:

<x-dynamic-component :component="$componentName" class="mt-4" />


Wednesday, September 2, 2020

PHP / MYSQL /LARAVEL Interview Questions

 

  - PHP/MYSQL/LARAVEL Interview Questions

        
    
  1. Why we use htaccess?

  2. What is the difference between index, primary, and unique keys?

  3. Difference between the index and index key?

  4. What is the foreign key why used it?

  5. Difference between array() and [] in php?

  6. Why we use Abstract classes and interface in oops?

  7. Can we search MySQL records by concat alias name when concat 2 values?

  8. Is it necessary to make all methods abstract in abstract classes?

  9. Difference between interface and abstract classes?

  10. What are design patterns?

  11. Difference between array_search and in_array in PHP? 

  12. Difference between array_merge and array_combine in PHP? if we define a duplicate key in array _merge than what it will return?

  13. When we use any class and declare construct and a magic method, which method is called the first construct method or magic method?

  14. What is abstract class why we use this?

  15. What is inheritance? Please give an example?

  16. Define hooks and their types?

  17. Why we use array_unique?

  18. What do u understand by interface why we use it?

  19. How to set database settings in laravel?

  20. How to use multiple databases in a single laravel application?

  21. How to use multiple languages in laravel?

  22. Why we use collation in MySQL.

  23. What are web services? how can we use it in laravel?

  24. What is the Mysql engines? which is better MyISAM or InnoDB?

  25. How we can define logs in laravel?

  26. What is array_flip?

  27. Difference between array_shift and array_unshift?

  28. how to export XML DB in MySQL?

  29. What is middleware in laravel? Please give 1 example.

  30. How can we run migrations in laravel?

  31. What are seeders in laravel and how can we use it?

  32. How can we write test cases in laravel?

  33. What are the triggers in MySQL?

  34. What is the store procedure in MySQL?

  35. how to know the site is in HTML or HTML 5?

  36. What is the difference between include_once & Require_once? which one is better?

  37. Difference between max_execution_time and max input time?

  38. What are the commands and how can we use it in laravel?

  39. Describe the Laravel Structure?

  40. How to use Repositories in Laravel for Create APIs?

  41. How to create helpers and use them in laravel?

  42. Please describe endpoints used in Laravel APIs for delete and view records?

  43. How to setup Supervisor in Laravel?

  44. How to use queues in laravel?

Integration of Queue in Laravel

Integration of Queue in Laravel Introduction Laravel Queue is to enhances the laravel application performance and provides a smooth proc...