-
app/Jobs/Common/CreateItem.php
Open in GitHub// Look at the DB::transaction being used inside the job, to avoid half-failures during the job // Also, in this project, all Jobs interact with the Request // You can take a look deeper into getRequestInstance in app/Abstracts/Job.php // Final note: this job, in turn, calls several more jobs for the Taxes of each created item use App\Abstracts\Job; use App\Jobs\Common\CreateItemTaxes; use App\Models\Common\Item; class CreateItem extends Job { protected $item; protected $request; public function __construct($request) { $this->request = $this->getRequestInstance($request); } public function handle() { \DB::transaction(function () { $this->item = Item::create($this->request->all()); if ($this->request->file('picture')) { $media = $this->getMedia($this->request->file('picture'), 'items'); $this->item->attachMedia($media, 'picture'); } $this->dispatch(new CreateItemTaxes($this->item, $this->request)); }); return $this->item; } }
-
app/Jobs/Common/CreateItemTaxes.php
Open in GitHub// As you can see, this job uses DB Transaction as well class CreateItemTaxes extends Job { protected $item; protected $request; public function __construct($item, $request) { $this->item = $item; $this->request = $request; } public function handle() { if (!empty($this->request['tax_id'])) { $this->request['tax_ids'][] = $this->request['tax_id']; } if (empty($this->request['tax_ids'])) { return false; } \DB::transaction(function () { foreach ($this->request['tax_ids'] as $tax_id) { ItemTax::create([ 'company_id' => $this->item->company_id, 'item_id' => $this->item->id, 'tax_id' => $tax_id, ]); } }); return $this->item->taxes; } }
-
app/Http/Controllers/Api/Common/Items.php
Open in GitHubuse App\Jobs\Common\CreateItem; class Items extends ApiController { public function store(Request $request) { // The job is automatically put onto queue if it's configured $item = $this->dispatch(new CreateItem($request)); return $this->response->created(route('api.items.show', $item->id), $this->item($item, new Transformer())); } // ... other methods }