5

when I try to dispatch a job from a controller it works.

however when I do the same from a repository it gives me an error.

<?php

namespace App\Repositories\Retailer;

use App\Jobs\SlackJob;
use App\Traits\CreateOrderTrait;

class CreateOrderRepo
{
   use CreateOrderTrait;

   public function create($store_id)
     {
        $slackJob = new SlackJob("Test", 1);
        $slackJob = $slackJob->onQueue('high');
        $this->dispatch($slackJob);
     }
}

the error:

Call to undefined method App\Repositories\Retailer\CreateOrderRepo::dispatch()

Garine
  • 574
  • 5
  • 21

2 Answers2

3

Add the trait to dispatch the jobs:

use Illuminate\Foundation\Bus\DispatchesJobs;
Paras
  • 9,258
  • 31
  • 55
  • how is this different from `app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($job);`? i typically use that – abbood Oct 12 '18 at 14:50
  • It's just lengthier, nothing more. Usually you would like to do `dispatch($job)` or `Job::dispatch()` rather than `app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($job)` – Paras Oct 12 '18 at 15:15
1

change this

$this->dispatch($slackJob);

to this

dispatch($slackJob);
wheelmaker
  • 2,975
  • 2
  • 21
  • 32
  • Including the trait works as well as it puts the dispatch method into your class but I always prefer to see less code, especially when it's still very clear what's going on, personal preference though. – wheelmaker Oct 12 '18 at 14:31
  • How is `dispatch($job)` less code or less clear than `Job::dispatch()`? I think either way is fine, just personal preference. But I don't see either one being more code or less clear – Paras Oct 12 '18 at 15:16
  • If an extra use statement doesn't qualify as "more code" I'm not sure how to help you but thanks for reiterating my point that it's personal preference. – wheelmaker Oct 12 '18 at 15:28
  • Yeah makes sense, one whole statement! Wow, so much more code, totally makes sense! – Paras Oct 12 '18 at 17:00
  • 1
    Glad we could agree, also thank you for noting that your personal preference is different than my personal preference one something that's just personal preference. I'm not really a fan of superfluous comments either but I guess that's personal preference too. – wheelmaker Oct 12 '18 at 17:01