Including a bugfix, some cleanup, and some refactoring, I would do it as follow:
app/Console/Commands/GetFeeds.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
// Dont forget to import your Webshop and Product models here, I do not know where they are in your project.
use App\Webshop;
use App\Product;
class GetFeeds extends Command
{
protected $signature = 'webshops:get-feed';
protected $description = 'Import the feeds for all webshops';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$webshops = Webshop::all();
foreach ($webshops as $webshop) {
$client = new \GuzzleHttp\Client();
$url = $webshop->url;
$response = $client->request('GET', $url);
$feed = json_decode($response->getBody()->getContents(), true);
$products = [];
foreach($feed['datafeed']['programs'][0]['products'] as $product) {
$product = Product::updateOrCreate(
['sku' => $product['product_info']['sku']],
[
'title' => $product['product_info']['title'],
'price' => $product['product_info']['price'],
'url' => $product['product_info']['url'],
'webshop_id' => $webshop->id
]
);
$products[] = $product->id;
}
// delete any product for this webshop that is not in the current feed
Product::where('webshop_id', $webshop->id)->whereNotIn('id', $products)->delete();
}
}
}
This console command can be run from the scheduler, or via "php artisan webhops:get-feed"
Included some cleanup (the temp variables for Product::updateOrCreate where unnecessary) and a small bugfix: sku => category_id, I believe this should have been the SKU ?
On every updateOrCreate it will save the product's ID to an array so after the webshop import is done, we can delete every product for this webshop that is not in this list.
(change in your DB schema needed: I did not see a webshop_id on the product model, but it really should be in there if you want to be able to only delete products for a single webshop)
In your app/Console/Kernel.php:
<?php
namespace App\Console;
use App\Console\Commands\GetFeeds;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
GetFeeds::class
];
protected function schedule(Schedule $schedule)
{
$schedule->command(GetFeeds::class)->dailyAt('01:00');
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
This keeps your Kernel.php clean, and will still run your schedule every day at 01:00 AM