Setting Up, Creating and Updating a hasOne Relationship in Laravel

Not a lot on creating and updating a hasOne record so here’s what ended up working for me. I have my Site model and a SiteCache. SiteCache should have a single record per Site.

SiteCache migration¬†(the Site migration isn’t that important so I omitted it here)

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSiteCachesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('site_caches', function (Blueprint $table) { $table->longText('json_content'); $table->unsignedInteger('site_id'); $table->foreign('site_id')->references('id')->on('sites')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('site_caches'); } }

Site Model

<?php namespace App; class Site extends Base // base is a model that I extend, nothing of note in it { public function cache() { return $this->hasOne(SiteCache::class); } public function setCacheContent($content) { $data = ['json_content' => $content]; if($cache = $this->cache()->first()) { $cache->update($data); } else { $this->cache()->save( new SiteCache($data) ); } return $this; } }

SiteCache Model

<?php namespace App; class SiteCache extends Base { public function site() { return $this->belongsTo(Site::class); } }

In use

<?php $site = Site::first(); $site->setCacheContent($json);

The creating and updating of the cache record on the SiteCache page isn’t as fluent as I’d like but with a little helper method on the Site model all is good.