Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 No query results for model in queue

I am trying to learn laravel database queue from its official documentation. I have done configuration as given in documentation .

Here my jobs :

<?php

namespace App\Jobs;

use App\SearchLog;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendTicket extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $log;

    protected $searchLog = array();



    public function __construct(SearchLog $log , $data = array())
    {
        $this->log = $log;
        $this->searchLog = $data;
    }

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

      $this->log->create($this->searchLog);     
    }

In my controller I call like this

public function store(Request $request)
{
 $searchLog = array();
 // searchLog contains the data to be inserted into database 
 $log = new SearchLog();
 $this->dispatch(new SendTicket($log , $searchLog));
 }

When I run the php artisan queue:listen I get the error like

[Illuminate\Database\Eloquent\ModelNotFoundException] No query results for model [App\SearchLog].

But when I edit the jobs like this

//only edited code 
public function __construct($data = array())
{
    $this->searchLog = $data;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
  SearchLog::create($this->searchLog);   
}

And when call from like this

 public function store(Request $request)
 {
    $searchLog = array();
    // searchLog contains the data to be inserted into database 
    $this->dispatch(new SendTicket($searchLog));
 }

It works fine and the data is inserted .
Here, my question is :

  1. How to send the object to the queue ?
  2. What is best way to send data to queue so that we can process ?
like image 966
Kiran Subedi Avatar asked Oct 07 '15 05:10

Kiran Subedi


1 Answers

The problem is in the use Illuminate\Queue\SerializesModels;, which tries to serialize the SearchLog $log param which you're passing to the constructor. Since your model is not saved yet, it doesn't have the identifier.

According to Laravel documentation:

If your queued job accepts an Eloquent model in its constructor, only the identifier for the model will be serialized onto the queue. When the job is actually handled, the queue system will automatically re-retrieve the full model instance from the database.

The workaround would be to remove SerializesModels trait from the Job class you're willing to save your model in.

like image 147
Ronen Avatar answered Sep 29 '22 12:09

Ronen