From fa33aa2e8b9993864090c8a5e5f5949efdca78c6 Mon Sep 17 00:00:00 2001 From: Mohamed Jinas Date: Mon, 10 Aug 2020 06:18:09 +0500 Subject: [PATCH] Command that scrapes mihaaru --- app/Console/Commands/ScrapeMihaaruCommand.php | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/app/Console/Commands/ScrapeMihaaruCommand.php b/app/Console/Commands/ScrapeMihaaruCommand.php index a572ad9..c38953b 100644 --- a/app/Console/Commands/ScrapeMihaaruCommand.php +++ b/app/Console/Commands/ScrapeMihaaruCommand.php @@ -5,6 +5,7 @@ namespace App\Console\Commands; use App\Source; use Illuminate\Console\Command; use App\Services\MihaaruService; +use App\Topic; class ScrapeMihaaruCommand extends Command { @@ -43,9 +44,10 @@ class ScrapeMihaaruCommand extends Command $articles = (new MihaaruService)->scrape(); - foreach($articles as $article) - { - $source->articles()->firstOrCreate([ + foreach ($articles as $article) { + + // Attach the relationship between source and article and return the curren article instance + $articleModel = $source->articles()->firstOrCreate([ "title" => $article["title"], "url" => $article["url"], "author" => $article["author"], @@ -53,11 +55,18 @@ class ScrapeMihaaruCommand extends Command "body" => $article["content"], "guid" => $article["guid"], "published_date" => $article["date"], - + ]); + + collect($article["topics"])->each(function($topic) use ($articleModel) { + $topicModel = Topic::firstOrCreate([ + "name" => $topic["name"], + "slug" => $topic["slug"], + ]); + + $topicModel->articles()->syncWithoutDetaching($articleModel); + }); + } - - - } }