Laravel 5.1 - Return Data from Jobs?

laravel job return value
laravel chain jobs
laravel jobs
laravel run job manually
laravel check if queue is running
laravel queue_connection
laravel queue not working
laravel clear queue

I'm just starting to use Jobs in Laravel 5.1 and am wondering if it's a good practice to return data from a Job? I haven't seen any examples of that, but here's a scenario. Lets say its an internal Messaging System between Users:

// Controller Method 
public function store(Request $request)
{
     if (!$this->messageValidator->isValid($request->all())) {
          return redirect()->back()->withInput()->withErrors($this->messageValidator->getErrors());
      }

      $this->dispatchFrom(PostMessage::class, $request, [ 'user' => Auth::user() ]);

      return redirect('messages');
}

So the Job will take the request data and the User, and will perform several tasks

// In the PostMessage Job

public function handle( // dependencies here)
 {
       // Create a new Thread

      //  Add Message to the Database

      // Store Recipients of Message in the Database 

      // Send email notifications to all involced

     return $message_id;
}

At the end of the handle() method, I returned the $message_id so I can use it for a redirect in the controller:

return view('messages.show', $message_id);

Is this an acceptable practice, or are Jobs meant to perform tasks in a more isolated manner?

Or is perhaps not a good use of Jobs?

Normally Jobs are used for things you might want to queue to run in the background (asynchronously), so it's a bit odd to receive a return value from them.

I would move the database saving elsewhere, and only use the Job for email notifications:

// Controller Method 
public function store(Request $request, MessageGuru $messageGuru)
{
    if (!$this->messageValidator->isValid($request->all())) {
        return redirect()->back()->withInput()
                   ->withErrors($this->messageValidator->getErrors());
    }

    $messageId = $messageGuru->store($request->all());

    $this->dispatchFrom(PostMessage::class, $request, [ 'user' => Auth::user() ]);

    return view('messages.show', $messageId);
}

// MessageGuru
class MessageGuru {

    public function store ($input) {
        //  Add Message to the Database

        // Store Recipients of Message in the Database 
    }
}

// In the PostMessage Job
public function handle()
{
    // Send email notifications to all involved
}

I did check the Laravel source code, and the return value from the job is indeed returned if the job isn't queued, but using Jobs that way would restrict you from refactoring it into a queued job later.

Returning Data from a Job?, I'm just starting to use Jobs in Laravel 5.1 and am wondering if it's a good practice to return data from a Job? I haven't seen any examples of  I'm just starting to use Jobs in Laravel 5.1 and am wondering if it's a good practice to return data from a Job? I haven't seen any examples of that, but here's a scenario. Lets say its an internal Messaging System between Users:

Since Laravel 5 Commands were replaced with Jobs, according documentation. That´s the official story. Unofficially there are still Commands and Jobs.

Commands extend Command class, and Jobs the Job class. I use them both myself. Commands to trigger Laravel stuff from command line and Jobs to queue tasks.

I´m actually looking for a possibility to retrieve data from a queued Job while it is running and use it in another Job. This thread hints, Commands or Events or shared Objects might do the trick, but i have to figure out the architecture myself it seems.

Queues - Laravel, Master, 7.x · 6.x · 5.8 · 5.7 · 5.6 · 5.5 · 5.4 · 5.3 · 5.2, 5.1, 5.0 · 4.2. Icon A null queue driver is also included which simply discards queued jobs. @param User $user * @return void */ public function __construct(User $user) @return void */ public function boot() { Queue::after(function ($connection, $job, $data) { // })  Return data from Laravel Jobs. Ask Question Asked 3 years, 7 months ago. Active 3 years, 7 months ago. Viewed 6k times Laravel 5.1 - Return Data from Jobs? 2.

I don't think the accepted answer exactly answers the question... instead it offers a 'better' approach (which I agree with). I wanted to try and answer the question itself, so I'm adding my 2 cents.

In Laravel you can choose the connection to which you want to send the job.

So you can definitely use the default connection for queued (async) jobs, as it's intended since version 5, and use the 'sync' connection for anything 'command-bus-like' from the previous version.

You can even add a new connection and call it anything you want (for example 'bus') and have it use the 'sync' driver, just so it will be clearer and so you'll have a differentiation between the 'sync' connection which is meant for testing locally and the command-bus purpose that you look for.

Then you just specify the connection you want to use when you dispatch the job:

ProcessPodcast::dispatch($podcast)->onConnection('bus');

I also miss the command bus idea sometimes, and this how to use it :-)

Hope this helps!

HTTP Responses - Laravel, Master, 7.x, 6.x · 5.8 · 5.7 · 5.6 · 5.5 · 5.4 · 5.3 · 5.2 · 5.1 · 5.0 · 4.2 A null queue driver is also included which discards queued jobs. Binary data, such as raw image contents, should be passed through the base64_encode function before This method will return an instance of the model with no loaded relationships: EvanDarwin changed the title Job fails to run and gets stuck in queue when a dependent model is deleted [5.1] Jobs fail to run when a dependent model is deleted Jun 20, 2015 This comment has been minimized.

Short answer: no.

Jobs are exactly that: a job that can be ran with no context. You should be able to run a job now, in a couple of seconds’ time, or in a year’s time. You give a job some data, and it should be executable at any time in the future.

If you need return data, maybe consider raising an event during the job’s execution. If you need the value of something after it’s happened, consider using a command or service object.

Views & Responses - Laravel, The most basic response is returning a string from a route or controller. Redirecting to a new URL and flashing data to the session are usually done at the  Laravel queues provide a unified API across a variety of different queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. Queues allow you to defer the processing of a time consuming task, such as sending an email, until a later time. Deferring these time consuming tasks drastically speeds up web requests to your

queue. When the job - Lumen, If you need access to the Response class methods, but want to return a view as the response content, you may use the Returning A Redirect With Flash Data. This Cron will call the Laravel command scheduler every minute. When the schedule:run command is executed, Laravel will evaluate your scheduled tasks and runs the tasks that are due. Defining Schedules. You may define all of your scheduled tasks in the schedule method of the App\Console\Kernel class. To get started, let's look at an example of

HTTP Requests - Laravel, 5.1. Master · 7.x · 6.x · 5.8 · 5.7 · 5.6 · 5.5 · 5.4 · 5.3 · 5.2 · 5.1 · Documentation · Laracasts By default, all of the queueable jobs for your application are stored in the @param Mailer $mailer * @return void */ public function handle(Mailer Queue::failing(function ($connection, $job, $data) { // Notify team of failing job. Laravel's events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. Don't worry if you don't see these directories in your application, since they will

Upgrade Guide - Laravel, @param Request $request * @return Response */ public function store(Request You may also retrieve all of the input data as an array using the all method: Questions: I am testing the queue functions in Laravel 5.1. I can make jobs queue up in my db table, called jobs, and I can get them to run successfully. I also created a queue failure table called failed_jobs.

Comments
  • As long as you're not queuing the job, returning from your Job is fine, if a bit unconventional. I definitely wouldn't call it a "good practice", since you won't be able to easily refactor it into a queued job. Note that you'll need $result = $this->dispatchFrom(.... But if you're sending email notifications, you're probably going to want to queue this instead of firing the job synchronously, in which case you won't have access to its return value.
  • @Ben thanks for your comment Ben. It seems that perhaps I'm misusing Jobs, in which case, where might this sort of Logic be placed?
  • I'd move the database saving to the Controller::store(), and use a queued job for the email notifications. That way you have access to the created $messageId.
  • By the way, your // Create a new Thread comment ruins the idea of getting the return value -- if you process the Job asynchronously, it can't return a value to your primary thread. You'd need to use some other communication channel such as DB/events/etc.
  • @Ben well like I said, I'm not doing this asynchronously. Which is why im asking if Jobs are the best place for this code. I know emails make sense there. But perhaps these sequential tasks do not. Moving the tasks back into the Controller also seems like the thing I'm trying to avoid -- tons of business logic right in the Controller method
  • did you ever come up with an architecture for this? I want to chain jobs together into larger jobs where each of the sub-jobs passes data on to the next job in the chain. Any thoughts?
  • @corradomatt: i didnt follow that issue anymore
  • But in Laravel 5.1, Commands have been replaced by Jobs. Which is why I tried this idea in the first place, because previously, a command seemed suitable
  • That doesn’t stop you from creating your own command classes. Just because it doesn’t exist in the framework doesn’t mean you can’t do it.
  • Sure, thats fair. However, if Jobs (as described by Laravel) are the same thing as Commands in the previous version, and uses the Command Bus and has a handle() method, then is it not suitable to make a Job?
  • I suggest to give it a try. It may end up as a hack but if it works there is no reason to stick to the official way. The framework should be used as a supportive tool, not taken as a restriction.