Hello
I'm fairly new to Laravel and could use a few tips. As a network engineer, I'm trying to automate a few tasks.
I'm trying to create an application which also consumes an external API.
I want a user of my application be able to create a network based on the unique AS number.
I then want my laravel application to fetch the information from that network via the API from peeringdb.
For example for google, the url would be peeringdbcom/api/net?asn=15169
The information collected, I want to store in my database for configuring my routers afterwards.
I want my application to fetch this information every 6 hours to keep my own database updated.
I'm using jetstream with livewire
I can't really figure out where I should place the http client.
Do i put this in a controller or are there better places?
I've got it working I believe. Are there ways to improve this code?
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Jobs\updateNetwork;
use App\Models\Network;
class UpdateNetworkInformationFromPeeringDB extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'networks:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update the network information via the PeeringDB API';
protected $networks;
protected $network;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$networks = Network::where('sync_with_peeringdb', 1)->get();
foreach ($networks as $network) {
UpdateNetwork::dispatch($network);
}
return 0;
}
}
<?php
namespace App\Jobs;
use App\Models\Network;
use Illuminate\Support\Facades\Http;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class updateNetwork implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $network;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Network $network)
{
$this->network = $network;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$network = $this->network;
$url = 'https://peeringdb.com/api/net?asn=' . $network->asn;
$request = Http::get($url);
$response = $request->json();
$network->as_set = $response['data']['0']['irr_as_set'];
$network->ipv4_max_prefixes = $response['data']['0']['info_prefixes4'];
$network->ipv6_max_prefixes = $response['data']['0']['info_prefixes6'];
$network->save();
}
}
protected function schedule(Schedule $schedule)
{
$schedule->command('networks:update')->hourly();
}