DEV Community

Sarthak Mahulikar
Sarthak Mahulikar

Posted on

Laravel Jobs : Step By Step Implementation

What is Laravel Jobs?

Job refers to tasks that are executed asynchronously. Laravel provides a powerful queue system for managing and executing these jobs. Job can be any PHP code that needs to be executed outside of the typical request-response cycle.

Why are Laravel jobs necessary?

In a synchronous system, users have to wait until the task is completed. It will lead to long waiting time, sometimes it happens when the tasks are resource intensive. In such situations laravel jobs come into play.
Laravel jobs provides you the functionality to handle the tasks in background, so it helps you for returning the web requests quickly.

When to use Laravel jobs?

The scenarios where laravel jobs are effective are as below:
1.Email Sending: In sending emails to the user jobs help you handle the requests. This ensures that the user don't need to wait for long time for getting response. When you handle request using laravel job you can send the response to the user while at the same time the job task is working in the background.

2.Data Processing: Sometimes while storing the different forms of data such as image, documents. You need upload those data to a particular platform but storing it without job makes it more time consuming. Hence laravel jobs helps you to run and handle these processes in background and helps to minimize request-response cycle time.

3.Notifications: If you have a system that sends notifications to the user you can use job for sending those notifications. You can schedule the notification job, laravel also provide the scheduling facility for the job such as daily, weekly ,etc. notifications.

Implementation Steps for Using Laravel Jobs

Step-I:
For getting started with larevel jobs you will need a database table that holds the jobs. To generate migration related to that creates the table for job, run queue:table Artisan Command and after migration is created. Use migrate command.

php artisan queue:table

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Now, you need to update the database driver by updating the value of QUEUE_CONNECTION variable mentioned in .env file of your application.

QUEUE_CONNECTION=database
Enter fullscreen mode Exit fullscreen mode

Step-II:
For creating jobs we have make:job Artisan command. All the jobs you have created by default stored in the app/jobs directory.
If the app/jobs directory doesn't exist in your application, you need not have to worry it will be created when you run the make:job Artisan commmand.

php artisan make:job <job_name>
Enter fullscreen mode Exit fullscreen mode

The code you want to execute after running job should be written in the handle() method

public function handle(): void
{
    // Write code here which you want to execute after running job
}
Enter fullscreen mode Exit fullscreen mode

For Running the jobs we have queue:work Artisan command.This command will start the queue worker and process the new jobs as they are pushed onto the queue. Once the queue:work command started, it will run continuously until you stop it manually or you close the terminal window.

php artisan queue:work
Enter fullscreen mode Exit fullscreen mode

Example: Filtering Posts For Inappropriate Words

In this example we will provide functionality to user that he can add post only which doesn't have any bad words If it has bad words then we will delete the post using the jobs.
The code for the above is as below:

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

    /**
     * Create a new job instance.
     */
   private $postId;

    public function __construct($post_id)
    {
        $this->postId=$post_id;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $post=Post::find($this->postId);
        $badWords=["Donkey","Bloody","Damn","Dumb"];
        $badWordsFoundList=[];
        foreach($badWords as $badWord )
        {

                if(Str::contains($post->description,$badWord))
                {

                    array_push($badWordsFoundList,$badWord);
                }

        }
       if(count($badWordsFoundList)!=0)
        {   $badWordsString='';

            foreach($badWordsFoundList as $badWordFound){
                $badWordsString.=" ".$badWordFound."  ";
            }

            echo "Deleting the post \n\n";
            $post->delete();

           echo 'bad words found  the words are: '.$badWordsString;
        }      
        else{

            echo " Bad Word not found in the Post ";
        } 
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Laravel job provide a efficient solution for executing asynchronous tasks in your application and thus saves your time and improves efficiency of application. These are the steps that are required for creating a job in Laravel

Top comments (0)