Question

I'm trying to import a mailing list from CSV to my DATABASE. I have two models in my Laravel which is responsible for doing this: Target and Mailing (one Target has many Mailings)

I'm using Queue system with Beanstalkd. I'm using:

Queue::push('ImportCSV', array(
            'file' => $file->getClientOriginalName(),
            'target' => $name
    ));

To push my jobs and then I have the ImportCSV job class:

class ImportCSV
{
public function fire($job, $data) 
{   
    Log::info("Starting to add {$data['target']} to database");

    $target = new Target();
    $target->name = $data['target'];
    $target->save();

    $reader = new \EasyCSV\Reader($data['file']);

    // There must be a Email field in CSV file
    /*if(!in_array('Email', $reader->getHeaders() ))
        throw new Exception("Email field not found", 1);*/

    while ($row = $reader->getRow())
    {
        $mailing = new Mailing();
        $mailing->target()->associate($target);
        $mailing->email = $row['Email'];
        $mailing->save();
    }

    Log::info("Mailing list {$target->name} added to database");

    $job->delete();
}
}

All the code seems to be working since I get these messages in my Log file

[2013-09-10 21:03:25] log.INFO: Starting to add TEst to database [] []
[2013-09-10 21:03:25] log.INFO: Mailing list TEst added to database [] []

But no records are added to my database. How should I use models inside a job? I already tested it in a Controller for example and everything works fine

Was it helpful?

Solution

Since you don't see other errors, I'm thinking this is an environment issue.

First - environments

Make sure your call to php artisan queue:listen (or queue:work, if applicable) is using the correct environment so the correct database is getting used:

$ php artisan queue:listen --env=YOUR_ENV

Here's a post on setting up queues in Laravel 4 which might be helpful for more information.

Second - namespaces

As you (apparently?) aren't seeing any PHP errors, this is less likely, but another idea:

If your class is namespaced, you may need to use the \ character to get your models, which are in the global namespace.

// From:
$mailing = new Mailing();

// To:
$mailing = new \Mailing();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top