Home > Enterprise >  Issues with running my first Job code in Laravel
Issues with running my first Job code in Laravel

Time:03-17

I'm trying to learn more about jobs in Laravel, I've created a job and am trying to write some code that pulls news data from a Final Fantasy 14 API and write it to the database, I have it scheduled to run every 30 minutes, but for some reason I'm running into issues when it comes to iterating over the json_decode() I have in a variable, here is the full function:

public function handle()
{
    $file = 'log.txt';
    $response = Http::get('https://lodestonenews.com/news/topics?locale=na');
    $articles = json_decode($response, true);

    foreach($articles as $article){
        $uniqueid = $article->id;
        $url = $article->url;
        $title = $article->title;
        $time = $article->time;
        $image_url = $article->image;
        $description = $article->description;

        $record = FF_News::where('uniqueid', '=', $uniqueid)->get();
        
        if($record === null) {
            
            $file = 'log.txt';
            file_put_contents($file, "ID - " . $article->id . " Not Found, Inserting in Database", FILE_APPEND);

            $newArticle = new FF_News;
            
            $newArticle->uniqueid = $uniqueid;
            $newArticle->url = $url;
            $newArticle->title = $title;
            $newArticle->time = $time;
            $newArticle->image_url = $image_url;
            $newArticle->description = $description;

            $newArticle->save();
        }else {
            file_put_contents($file, "Found ID - " . $article->id . " - Not writing to database", FILE_APPEND);
        }
    };
}

Please let me know if there is a better way of handling this or if there is something that I'm not quite doing right here. Thanks for any help in advance!

CodePudding user response:

Just some feedback to help I would create a temporary function to debug any issues you are getting as jobs will not return any errors straight away. All job errors appear in the laravel.log file. Finally I would get all of your api data in the controller and pass this to the job instead with a constructor! Hope this helps.

CodePudding user response:

I actually ended up finding the issue, it was silently failing due to me not having proper error handling to tell me what was going on, upon review of the laravel.log file, I found that it wasn't hitting the database table at all, I update the model to use that specific table and all is well now!

  • Related