Dad Builds $3,000 Chicken Coop To Get 16 Cent Eggs For Free

https://media.babylonbee.com/articles/article-10526-1.jpg

BIRMINGHAM, AL—According to sources, local dad Dave Manheart recently completed a project that will help enable his family to save money on groceries. After much research and 10 weekends of hard labor, Dave has succeeded in constructing a backyard chicken coop. With a small investment of just $3000 on lumber and supplies, he now can get 16¢ eggs for free.  

“With the supply chain issues and inflation, it’s important to be independent,” said Manheart. “Plus, this new chicken coop will look really great on my wife’s Instagram feed, which is what this whole thing is really about.”

Local witnesses described Manheart’s pride in the newly constructed chicken coop as “really cute.” His wife assured reporters that they will enjoy eating ten eggs a day since they are free.  

After leveling a spot in the backyard with a backhoe Dave rented for just $500, putting together the coop was fairly easy and only resulted in two trips to the emergency room with accidental injuries. “Dave says his back will be fine now that he’s no longer lifting lumber, and the doctors had no problem re-attaching his finger,” said his appreciative wife Deb.    

“Daddy bought the cutest little baby chicks!” said his little girl.  “But then our dog Buster ate them so we had to get new chicks.” The dog now has an $800 invisible fence to keep him away from the chicken coop.  

“That was totally worth it,” said Dave as he proudly surveyed his handiwork.

At the time of publication, the homeowners association had issued a fine of $500 for the unapproved chicken coop.

A Babylon Bee subscriber contributed to this report. If you want to get involved with the staff writers at The Babylon Bee, check out our membership options here!


Watch as this Joe Rogan fan fruitlessly tries to get Alexa to play the Joe Rogan Experience.

Subscribe to The Babylon Bee on YouTube

The Babylon Bee

Camp Perry Rifle Matches Scheduled for 2022 Season

Registration is now open for the Civilian Marksmanship Program’s (CMP) series of Garand, Springfield, Vintage and Modern Military (GSMM) rifle matches – set at Ohio’s historic Camp Perry National Guard Training Facility in 2022. Most people would know these events as the Camp Perry Rifle Matches.

RELATED STORY

Brian Zins wins NRA National Pistol Championships at Camp Perry for 10th time.

Electronic Scoring Means More Efficient Matches

Camp Perry’s Petrarca Range will host these matches. The Petrarca Range has an advanced electronic scoring system called KTS. Utilizing these KTS (Kongsberg Target System) targets means faster competition time, with no need for pit duty, and added ease for competitors who can rely on instant, accurate shot monitors located at each firing point.

Dates for the 2022 Camp Perry Rifle Matches at Petrarca Range currently include:

  • Sunday, April 3
  • Saturday, June 25
  • Saturday, Sept. 17

Competitors of all skill levels are welcome to attend these recreational events. These events create a comforting environment for marksmen new to fundamental match procedures. Additionally, these matches also challenge seasoned athletes through friendly competition. Knowledgeable CMP staff members will be on hand at all events to ensure safety and to answer questions.

In addition to the Petrarca matches, a set of highpower rifle 800 Aggregate and Excellence-In-Competition (EIC) events are on the schedule. The host range for these events is Camp Perry’s outdoor Viale Range, on June 25-26, 2022. The matches are ideal for those in the hunt for a Distinguished Rifleman Badge. The Viale matches utilize CMP’s highpower electronic target line and offers the same conveniences as the Petrarca targets. Registration for the matches is available on the CMP website at https://thecmp.org/competitions/matches/camp-perry-matches/.

Space is limited for these events, so sign up today! Additionally, you can find more information, including registration links and an in-depth look into the inner workings of Petrarca’s electronic target system, at https://thecmp.org/ranges/cmp-targets-at-petrarca-range/.

Petrarca is also open weekly!

Petrarca Range will open for public use starting March 14, 2022. Every Monday, guests may use Petrarca during the hours of 9 a.m. to 5 p.m., March through May and September through November. During the summer months (June through August), Petrarca is open from 9 a.m. until 6 p.m. 

Please note: During the National Matches (July 11-Aug. 13), Petrarca Range will be open throughout the week after firing is complete on Rodriguez Range or may be closed due to matches/clinics being held on Petrarca Range. See the detail schedule at https://thecmp.org/ranges/cmp-targets-at-petrarca-range/.

(Editor’s note: this article, with minor changes, was contributed by the CMP Staff Writer Ashley Brugnone)

The post Camp Perry Rifle Matches Scheduled for 2022 Season appeared first on Tactical Life Gun Magazine: Gun News and Gun Reviews.

Tactical Life Gun Magazine: Gun News and Gun Reviews

How to Turn an Older Mac or PC into a Chromebook

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/a33d15a4382069f9c826be4f629793af.jpg

Photo: Konstantin Savusia (Shutterstock)

Before you take your sluggish old computer down to the e-waste disposal site, try bringing it back to usefulness by installing a Chrome operating system. Google has opened the downloading gates to Chrome OS Flex, a new iteration of its versatile OS, and it might be the perfect solution if your older Mac or PC is having trouble swallowing updates to its native operating system.

Flex is designed to modernize older computers by installing a leaner, cloud-focused OS. While it doesn’t have all of Chrome’s features, Google promises it will basically make your Mac or PC look and feel like a Chromebook running Chrome OS.

Google says Chrome OS Flex will provide a “fast, modern work experience from anywhere” that will make your gear boot faster, access VDI (virtual desktop interface) and web apps quickly, and prevent it from slowing down over time. Plus, it’s free.

While overhauling your computer with Chrome OS isn’t a new hack—CloudReady came out in 2015—Flex OS provides more flexibility that warlier options by offering dual-booting, allowing users to easily switch between operating systems with a simple restart.

Before you install Chrome OS Flex, know that it is in early access mode, so there could be bugs/instability. Also, it won’t do everything Chrome OS does—some features are dependent on the hardware you’re using to run the OS, and Google Play and Android apps aren’t supported at all. (Here’s Google’s list of the differences between Chrome and Chrome OS Flex if you need more details.)

How to install Google OS Flex on your laptop or desktop

  • Get a USB drive—8GB or larger.
  • Register yourself.
  • Read (and follow) the instructions for creating a Chrome OS Flex USB boot stick.
  • Reboot your computer with Chrome OS Flex USB inserted.
  • Enjoy your Chrome-based computer.

I tried this out, and installation was as easy as promised. I offer you the above photographic proof that my 12 year-old iMac is now an iChromeFlexMac (or something.)

  

Lifehacker

ChromeOS Flex is an ideal off-ramp for millions of PCs that can’t run Windows 11

https://cdn.arstechnica.net/wp-content/uploads/2022/02/google-chrome-flex-760×380.jpg

ChromeOS Flex is an ideal off-ramp for millions of PCs that can’t run Windows 11

Aurich Lawson

October 14, 2025, marks the end of support and security updates for the Home and Pro versions of Windows 10. That means it’s also the end of official guaranteed feature and security updates for Windows PCs that don’t meet Windows 11’s hardware requirements.

Viewed from early 2022, that date is still comfortably far off. Lots of Windows 10 PCs will break over the next 3.5 years, and plenty of people who actually want to upgrade to nicer or faster hardware will have opportunities to do so. But as someone who enjoys repairing, maintaining, and upgrading older hardware to keep it useful, we’ll be peering over the edge of that Windows 10 update cliff before we know it.

The question is: what happens to that hardware when Windows 10 goes away? Running Windows 11 on unsupported hardware is one possible solution, but we have no idea for how long Microsoft will actually allow installing, running, and updating Windows 11 on older PCs; the company could cut off these computers’ security updates tomorrow, or it could allow them to run the new OS indefinitely, and that uncertainty is hard to plan around.

A Linux distribution is another option, particularly the more user-friendly distributions like Ubuntu, Mint, or Elementary OS. But “user-friendly” is relative, and any Linux distribution can have parts that are obtuse and difficult for newcomers to learn. And, let’s face it, if a Linux distribution was going to truly compete with and succeed against Windows on consumer desktops and laptops, it probably would have by now.

Enter ChromeOS Flex, a Google-blessed and Google-supported version of its lightweight Linux operating system that will run on most standard PC hardware. It’s a successor to CloudReady, a ChromiumOS-based product that Google purchased in late 2020 and that we’ve covered since its very early days as a way to make aging PCs into ersatz Chromebooks.

ChromeOS (also Linux-based, but mostly trying to hide it) has managed to find a toehold in the Windows-and-macOS-dominated world of consumer PCs thanks in part to its simplicity, the backing of a large and well-resourced company, and easy-to-use management tools for schools and businesses. And with Flex, Google is offering those organizations the opportunity to switch their Windows laptop fleets to ChromeOS fleets virtually overnight, while also offering users of aging PCs an alternative OS to try.

We’ve downloaded and installed the first developer version of ChromeOS Flex and read through all of its documentation to figure out the kind of hardware it will run on and how it’s different from the CloudReady operating system it’s replacing.

Beware: Beta

The same tool you use to make ChromeOS recovery media will also make ChromeOS Flex media. And this one USB drive can cover all PCs.

Enlarge / The same tool you use to make ChromeOS recovery media will also make ChromeOS Flex media. And this one USB drive can cover all PCs.

Andrew Cunningham

You’ll find ChromeOS Flex listed among all the “real” Chrome hardware in the official Chromebook Recovery Utility. Select ChromeOS Flex as your device manufacturer and the dev channel build of Flex will show up. There’s no need to download different images for different devices or CPU types. The installation documentation is pretty clear and has lots of details if you need them.

The dev channel build of Flex, based on ChromeOS version 100, is clearly a pretty early version of the operating system. It’s still labeled as “CloudReady” in more than one place, and Google’s list of certified models is filled with reminders to expect minor or major issues. As with CloudReady, it’s possible to run ChromeOS Flex entirely from the USB install drive if you want to try the OS without formatting your internal storage, and that’s what we’d recommend for now.

System requirements and “supported hardware”

At a very bare minimum, ChromeOS Flex doesn’t need much to install and boot, especially compared to Windows 11:

  • A 64-bit x86 processor (ARM isn’t supported, nor are 32-bit CPUs)
  • 4GB of RAM
  • 16GB of internal storage
  • USB booting support and full administrator access to the BIOS

Google does note that “components made before 2010 might result in a poor experience.” And if you’re trying to install the OS on an old Intel Atom PC, you might also be out of luck—Intel’s GMA 500, 600, 3600, and 3650 integrated GPUs “do not meet Chrome OS Flex performance standards.” Broadly, though, if a PC runs the 64-bit version of Windows 10 reasonably well, then it should at least boot and run.

To get the best, most Chromebook-like experience—and to be eligible for Google-provided software and hardware support—Google will maintain a list of certified hardware models that it will individually test, troubleshoot, and optimize for. Google’s list of certified models looks pretty similar to Neverware’s list of certified models for CloudReady, which means that it’s heavily weighted in favor of business laptops and desktops. But it includes hardware going all the way back to first-generation Intel Core PCs (and even a handful of Core 2 Duo models), which casts a pretty wide net. Unlike Neverware, Google hasn’t published end-of-support dates for any of these models. But assuming it continues to use Neverware’s timeline, most certified models can expect software support for 13 or 14 years after they were originally introduced.

Google doesn’t require either Secure Boot support or a TPM to install or run ChromeOS Flex, but it recommends that you enable both on PCs that support them. Without the Google-sanctioned security hardware, ChromeOS Flex PCs don’t support ChromeOS’s Verified Boot feature, but enabling Secure Boot “maintain[s] the same boot security as Windows devices.” And having an enabled and working TPM 1.2 or 2.0 module allows for more secure device encryption and support for hardware-backed certificates, among other things. If you’re switching to ChromeOS Flex from Windows, you may need to clear your TPM and then re-enable it so that ChromeOS can use it.

For testing, I used many of the same aging PCs that I used when testing Windows 11 on unsupported hardware. I had the best experience on the newest of those PCs, a 2016-era Dell Latitude 3379 two-in-one with a Core i3-6100U and 8GB of RAM. But Flex also installed and ran OK on an older Windows 7-era HP Pavilion dv5 with a Core i3-540 and 4GB of RAM, albeit with some graphical artifacts and no audio coming out of the speakers (admittedly, this laptop is nowhere on the certified hardware list, though a few other systems of the same vintage are listed).

Hardware limitations

Even assuming that you’re running it on certified hardware, Google has a list of PC features that Flex won’t support and hardware functionality that it isn’t guaranteeing. This includes biometric login devices like fingerprint scanners and IR cameras, SD card readers, display outputs, optical drives, FireWire and Thunderbolt ports (though Thunderbolt 3 and 4 ports should work fine in USB-C mode), and stylus and pen input. External Wi-Fi dongles “often work,” but Google isn’t testing them specifically.

Google also says that boot speed, power-saving features, and battery life might be affected when you install ChromeOS Flex, even on fully certified models. This is par for the course for Linux running on most PCs or Macs, which generally works fine but can reduce battery life because the software hasn’t been optimized for the particular hardware you’re running it on.

Ars Technica

Canada shows us that it’s time to prepare for the worst

https://media.notthebee.com/articles/620b9e16e66eb620b9e16e66ec.jpg

In 1775, delivering one of the greatest speeches in American history, Patrick Henry urged the Second Virginia Convention to prepare for the "clash of resounding arms" coming from the burgeoning Revolutionary War.

Not the Bee

Google’s New Chrome OS Flex Will Rescue Your Old PC or Mac

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/1c2ff8c7229ce469bb24f14cb0effd63.gif

Google today announced a new operating system, Chrome OS Flex, free-to-use, cloud-based OS built to convert old PCs or Macs into Chromebooks.

The new OS was developed by Google a few years after acquiring Neverware—the makers of Cloudready—and was primarily made for schools and businesses with fleets of old PCs or Macs that have been bogged down after years of use. Google argues these systems could be revitalized by stripping out Windows or macOS and installing Chrome OS Flex, a lightweight operating system that can run on weaker hardware and remain stable for years due to its reliance on the cloud. Most importantly, Chrome OS Flex will get the same attention from Google as Chrome OS—that is, it relies on an identical code base and will receive the same release cadence.

Thomas Riedl, director of product for enterprise and education on Chrome OS, told us that Google invested heavily in ensuring that UIs are consistent across both operating systems and brought primary Chrome OS features, including the Google Assistant, Chrome browser, and cross-device Android tools, to Flex.

“With such similar end-user and IT experiences, it’s also easy to transition from Chrome OS Flex to Chrome OS devices when you’re ready to purchase new hardware: With Chromebooks, Chromeboxes, and Chromebases, you’ll experience end-to-end optimization across hardware and software with the strongest security and largest app ecosystem through the Google Play Store,” Riedl wrote in a blog post.

Chrome OS Flex could be a saving grace for businesses attempting to operate with a mixed fleet of older Mac or PCs and newer Chromebooks. Those aging systems could not only be given new life running Chrome OS Flex but with Chrome Enterprise Upgrade, they can be managed within the same Google Admin console as newer Chrome OS devices. It would also be much easier to move everything over from Flex to a new Chromebook when it’s time for a hardware upgrade.

“Oftentimes, Windows forces them [consumers] to use systems for shorter than they should. We have Chrome ready for you and you don’t have to buy new hardware,” Riedl said. He went on to say that the first 100 Chrome OS releases were on Google’s own devices, but the next will be on “whatever hardware you throw at it.”

Google also makes a sustainability argument in that moving to Chrome OS Flex could rejuvenate laptops that are on life support before they’re shipped off to a landfill. Businesses might also switch to Chrome OS Flex for specialized hardware like kiosks and digital signage, and in one extreme use case, a Scandinavian hotel chain switched to Chrome OS (using CloudReady) to flee from a ransomware attack.

Google says Chrome OS Flex can run efficiently on devices that are up to 13 years old—a bold claim we are eager to try out once we can get our hands on an Apple PowerBook G4.

“You can go back 10 or more years and people are still getting a really good experience. I do think you’ll get some advantages with speed or performance but one of the more profound things is that Windows won’t stay as performant on year five as on year one. Chrome OS Flex won’t age as poorly and won’t accrue that baggage over time,” Forrest Smith, a product manager for Chrome OS, told Gizmodo.

There are some notable limitations with Flex, most of which stem from using hardware made for another OS. For example, Chrome OS Flex devices running on PC or Mac hardware won’t have the same key shortcuts as Chromebooks. Moreover, certain device drivers aren’t compatible with Flex; as a result, the webcam on some MacBook models won’t function properly.

Riedl also concedes that while Flex is supposedly more secure than a PC, it isn’t quite as safe as a Chromebook given the software/hardware disconnect. Google says it will be transparent with customers in describing the risks of switching to Flex and plans to publish a list of certified device models with notes outlining which features do and don’t work.

While testing Chrome OS Flex is as easy as booting it from a USB drive—a process that should take about 30 minutes—replacing an OS with another across an entire fleet is non-trivial. Smith says that while IT admins are comfortable with the installation process, it isn’t something anyone can pull off. The long-term goal, however, is to simplify the process and broaden the adoption of Chrome OS Flex to individual users.

“At Google, we were very tempted to just go big and to put it out to everybody, but over the years, we’ve learned that having a focus is good. Our most loyal fans are those who tinker with it and try it out so what you’ll see is that you have an installer and can try it out yourself,” Riedl said.

These are still early days for Chrome OS Flex, and Google admits it hasn’t done any large-scale testing just yet. With this early access period, the company is giving users a chance to play around with the OS and provide feedback before it pushes it out to market. Those who want to give Chrome OS Flex a try can do so by loading it from a USB; this method gives you a “risk-free” way to try Chrome OS Flex before doing a full OS swap.

Google says a stable version of Chrome OS Flex will be made available “in the coming months” and to expect bugs in its current state. Those who were using CloudReady will be upgraded to Chrome OS Flex free of charge.

Gizmodo

Scramble the fighters! Thousands of protesters sign up to egg Jeff Bezos’ yacht at Dutch bridge site

https://cdn.geekwire.com/wp-content/uploads/2022/02/6102613335_e78d516e2d_k.jpg

The historic De Hef bridge in the Dutch city of Rotterdam. (Flickr Photo / Gerard Stolk)

Nearly 5,000 people have signed up to throw eggs at Jeff Bezos’ superyacht when it sails through the Dutch city of Rotterdam this summer. The planned protest comes in the wake of news that the billionaire Amazon founder’s $500 million vessel would require the dismantling of a historic bridge in order to reach open waters.

“It started more as a joke among friends after we heard the news about the possible dismantling of the bridge,” protest organizer Pablo Strörmann told the NL Times earlier this month.

But the joke, and the yolk, is “getting way out of hand,” he said.

A Facebook page for the event shows 4,800 people planning to attend and 16,200 more who are interested.

“Calling all Rotterdammers, take a box of rotten eggs with you and let’s throw them en masse at Jeff’s superyacht when it sails through the Hef in Rotterdam,” the event description reads.

The Hef is the nickname for the 95-year-old Koningshaven Bridge, a local landmark which stands in the way of the 417-foot-long triple-masted sailing yacht. The bridge has a clearance of 131 feet and city officials have given permission for the middle section to be removed and then replaced.

“Normally it’s the other way around: If your ship doesn’t fit under a bridge, you make it smaller,” Strörmann told the NL Times. “But when you happen to be the richest person on Earth you just ask a municipality to dismantle a monument. That’s ridiculous.”

Bezos’ yacht, known as Project Y721 and built by Alblasserdam, Netherlands-based Oceanco, will take on the title of world’s largest sailing yacht, among other records, upon delivery.

GeekWire

Introduction to Laravel caching

https://cdn.sanity.io/images/f1avhira/production/5899f504515cc5bdceae5764ed0b744b8e973aa3-2400×1256.png?w=1200

What is caching

A common pain point in applications is optimizing and reducing the number of trips you have to take to the database. Say you have an e-commerce admin dashboard. Maybe you have a page that displays all inventory — every product, associated category, vendors, and more. A single page like this may perform dozens of calls to your database before the page can even display any data. If you don’t think about how to handle this, your application can quickly become slow and costly.

One option to reduce the number of times you have to go to the database is through caching. Caching allows you to store specific data in application memory so that next time that query is hit, you already have the data on hand and won’t have to go back to the database for it. Keep in mind, this is different from browser caching, which is user-based. This article covers application caching, which happens at the application level and cannot be cleared by the user.

Laravel has robust built-in functionality that makes caching a breeze.

Let’s see it in action!

Set up a database

For this demonstration, you will use a PlanetScale MySQL database to get a practice database up and running quickly. I promise this setup will be fast and painless!

  1. Create a free PlanetScale account.

  2. Create a new database either in the onboarding flow or by clicking “New database” > “Create new database“.

  3. Give your database a name and select the region closest to you.

  4. Click “Create database“.

    PlanetScale modal to create a new database

    Once it’s finished initializing, you’ll land on the Overview page for your database.

    PlanetScale database overview page

  5. Click on the “Branches” tab and select the main branch. This is a development branch that you can use to modify your schema.

PlanetScale has a database workflow similar to the Git branching model. While developing, you can:

  • Create new branches off of your main branch
  • Modify your schema as needed
  • Create a deploy request (similar to a pull request)
  • Merge the deploy request into main

Diagram showing the PlanetScale workflow described above

Leave this page open, as you’ll need to reference it soon.

Set up Laravel app

Next, let’s set up the pre-built Laravel 9 application. This comes with a simple CRUD API that displays random bogus sentences (we’re going to think of them as robot quotes) along with the quote author’s name. The data for both of these columns are auto-generated using Faker. There is currently no caching in the project, so you’ll use this starter app to build on throughout the article.

For this tutorial, you’ll use the default file-based cache driver, meaning the cached data will be stored in your application’s file system. This is fine for this small application, but for a bigger production app, you may want to use a different driver. Fortunately, Laravel supports some popular ones, such as Redis and Memcached.

Before you begin, make sure you have PHP (this article is tested with v8.1) and Composer (at least v2.2) installed.

  1. Clone the sample application:

    git clone -b starter https://github.com/planetscale/laravel-caching
  2. Install the dependencies:

    
    
  3. Copy the .env.example file to .env:

    
    
  4. Next, you need to connect to your PlanetScale database. Open up the .env file and find the database section. It should look like this:

    DB_CONNECTION=mysql
    DB_HOST=<ACCESS HOST URL> 
    DB_PORT=3306
    DB_DATABASE=<DATABASE_NAME> 
    DB_USERNAME=<USERNAME>
    DB_PASSWORD=<PASSWORD>
    MYSQL_ATTR_SSL_CA=/etc/ssl/cert.pem
  5. Go back to your PlanetScale dashboard to the main branch page for your database.

  6. Click “Connect” in the top right corner.

  7. Click “Generate new password“.

  8. Select “Laravel” from the dropdown (it’s currently set to “General”).

  9. Copy this and replace the .env content highlighted in Step 4 with this connection information. It’ll look something like this:

    DB_CONNECTION=mysql
    DB_HOST=xxxxxxxx.xx-xxxx-x.psdb.cloud
    DB_PORT=3306
    DB_DATABASE=xxxxxxxx
    DB_USERNAME=xxxxxxxxxxxxx
    DB_PASSWORD=pscale_pw_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    MYSQL_ATTR_SSL_CA=/etc/ssl/cert.pem

    Make sure you save the password before leaving the page, as you won’t be able to see it again.

    Note: Your value for MYSQL_ATTR_SSL_CA may differ depending on your system.

  10. Run the migrations and seeder:

    php artisan migrate
    php artisan db:seed
  11. Start your application:

    
    
  12. You can now view your non-cached data from the PlanetScale database in the browser at http://localhost:8000/api/quotes.

Project structure overview

Before diving in, let’s explore the project and relevant files.

Quote controller

The sample application has a single controller, app/Http/Controllers/QuoteController.php, that has methods to display, update, create, and delete quotes. Since this is an API resource controller, you don’t need to include the usual show and edit controllers that only return views.

You’ll take a closer look at this soon once you add caching, but right now, nothing is cached.

Quote model

There’s also a model, app/Models/Quote.php, where you can define how Eloquent interacts with the quotes table. Since you only have one table in this application, there are no relationships or interactions, so the model is pretty barebones right now:

class Quote extends Model
{
    use HasFactory;

    public $timestamps = FALSE;
    protected $fillable = [
        'text',
        'name'
    ];
    
}

You’ll revisit it soon, though, once you implement caching.

Quote migration

Next up is the initial quotes migration file, database/migrations/2022_01_215158_create_quotes_table.php. When you ran the migrations in the previous step, this file created the quotes table with the specified schema:

public function up()
{
    Schema::create('quotes', function (Blueprint $table) {
        $table->id();
        $table->text('text');
        $table->string('name');
    });
}
Quote factory and seeder

Finally, there’s a factory and seeder. The factory, database/factories/QuoteFactory.php, uses Faker to create mock sentence and author data. The seeder, database/seeders/DatabaseSeeder.php, then runs this factory 100 times to create 100 rows of this Faker-generated data in the quotes table.

public function definition()
{
    return [
        'text' => $this->faker->realText(100, 3),
        'name' => $this->faker->name()
    ];
}

When you ran php artisan migrate and php artisan db:seed in the previous steps, these are the files that were ran.

Queries without caching

Before you add caching, it’s important to see how the application currently perform so you know the effect that caching has. And how will you do that if you don’t know what your query performance was before adding caching?

Let’s run some queries and see how long they take to complete.

Get all data

Open up the app/Http/Controllers/QuoteController.php file and go to the index() method. Replace it with:

public function index()
{
    $startTime = microtime(true); // start timer
    $quotes = Quote::all(); // run query
    $totalTime = microtime(true) - $startTime; // end timer

    return response()->json([
        'totalTime' => $totalTime,
        'quotes' => $quotes        
    ]);
}

The PHP function, microtime(true), provides an easy way to track the time before and after the query. You can also use an API testing tool like Postman to see the time it takes to complete.

Let’s call the API endpoint to check how long it currently takes to pull all of this data from the database.

Open or refresh http://localhost:8000/api/quotes in your browser. You’ll now see a totalTime value that displays the total time in seconds that it took to execute this query.

The total time will fluctuate, but I’m personally getting anywhere between 0.9 seconds and 2.3 seconds!

Of course, you’d want to paginate or chunk your data in most cases, so hopefully, it wouldn’t take several seconds to grab in the first place. But caching can still greatly reduce the time it takes to get data from this endpoint after the initial hit.

Let’s add caching now.

Add caching to your Laravel app

Open up app/Http/Controllers/QuoteController.php, bring in the Cache facade at the top of the file, and replace the $quotes = Quote::all(); in index() with:

// ...
use Illuminate\Support\Facades\Cache;

// ...
public function index() {
    // ...
    $quotes = Cache::remember('allQuotes', 3600, function() {
        return Quote::all();
    });
    // ...
}
// ...

Now let’s hit that API endpoint again. Refresh the page at http://localhost:8000/api/quotes. If this is your first time running the call, you’ll have to refresh again for the caching to take effect.

Check out the new time I’m getting: 0.0006330013275146484 seconds!

Before caching, this exact same query took between 0.9 seconds and 2.3 seconds. Incredible, right?

Even though this seems to be a massive improvement on the surface, there are still some issues that you need to tackle. Let’s first dissect the Cache::remember() method and then go over some gotchas with this addition.

Note — If at any time you need to clear the cache manually while testing, you can run the following in your terminal:


Caching with remember()

The Cache::remember() method first tries to retrieve a value from the cache. If that value doesn’t exist, it will go to the database to grab the value, and then store it in the cache for future lookups. You will specify the name of the value and how long it stores it, as shown below:

$quotes = Cache::remember('cache_item_name', $timeStoredInSeconds, function () {
    return DB::table('quotes')->get();
});

This method is super handy because it does several things at once: checks if the item exists in cache, grabs the data if not, and stores it in the cache once grabbed.

If you prefer just to grab the value from cache and do nothing if it doesn’t exist, use:

$value = Cache::get('key');

If you want to grab the value from cache and pull it from the database if it doesn’t exist, use:

$value = Cache::get('key', function () {
    return DB::table(...)->get();
});

This one is similar to remember(), except it doesn’t store it in the cache.

Inconsistent data in the cache

So what are the problems that you need to deal with? Let’s see one of them in action.

Refresh the [http://localhost:8000/api/quotes](http://localhost:8000/api/quotes) page in the browser one more time to make sure the cache hasn’t expired. Now, add a new record to the quotes table by pasting the following in your terminal:

curl -X POST -H 'Content-Type: application/json' -d '{
  "text": "If debugging is the process of removing software bugs, then programming must be the process of putting them in.",
  "name": "Edsger Dijkstra"
}' http://localhost:8000/api/quotes -i

You should get a HTTP/1.1 200 OK response along with the newly added record. Now go back to your Quotes page in the browser and refresh. The new data you added isn’t there! That’s because you just wrote this item to the database, but you’re not actually going to the database to retrieve it. The cache has no idea it exists.

You can confirm it was added to the database by going back to your PlanetScale dashboard, select the database, click “Branches“, and click “Console“.

Run the following command and you should see 101 records:


PlanetScale console select all query

Scroll to the bottom and you’ll see the newly added quote. You can also query it directly by id:

select * from quotes where id=101;

PlanetScale console select single quote query

Solving the write problem

If it’s important for your application to always show the most up-to-date data, one quick way to fix this is using the Quote model’s booted() method.

Open up app/Models/Quote.php and replace it with:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Quote extends Model
{
    use HasFactory;

    public $timestamps = FALSE;
    protected $fillable = [
        'text',
        'name'
    ];

    protected static function booted()
    {
        static::saving(function() {
            Cache::forget('allQuotes');
        });
    }
}

The booted() method allows you to perform some action when a model event fires. In this case, when saving() is called, you’re instructing Eloquent to forget the cache item named allQuotes.

Let’s test it out. Refresh your quotes page in the browser one more time to make sure everything is cached, then add another quote with:

curl -X POST -H 'Content-Type: application/json' -d '{
  "text": "Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Mondays code.",
  "name": "Dan Salomon"
}' http://localhost:8000/api/quotes -i

Now refresh again, and you’ll see the time to make this query has increased significantly, indicating that the database has been hit. You’ll also now see the new entry in the output! With this, you can be confident that the displayed quotes are always up-to-date.

The saving() method works on both new and updated records. However, if you delete something, the cache won’t be cleared. You can use the deleted() method to handle that.

First, try to delete something (replace the last number with the id of the item you want to delete):

curl -X DELETE http://localhost:8000/api/quotes/1 -i

Refresh the quotes page, and the item should still be there. Now, go back to your Quote model and add this in the boot() method underneath saving():

static::deleted(function() {
    Cache::forget('allQuotes');
});

Run that cURL command one more time, but with a different id, to trigger a delete event. Refresh again and those records should now be gone!

More Laravel caching strategies

As you’ve seen, when it comes to caching, you’re going to have to think about a few things specific to your application before diving in.

Retrieving data

How long do you want to store the data in cache? The answer to this depends on the data. Is this data relatively static? Or does it change a lot? When a set of data is requested, how important is it that it’s always up to date? These questions will help you decide how long to cache the data and if you should cache it at all.

Storing/updating/deleting data

This tutorial covered caching retrieved data. But you can also store new or updated data in the cache as well. This is called write caching. Instead of going to the database every time you need to add or update something, you store it in the cache and eventually update it all at once.

Deciding the time at which you update actually leads to more questions. What if you wait too long and there’s a system failure? All of the cached data is gone. What if someone makes a request to see a product price, but that price has changed, and you’ve been storing the update in cache? The data between the cache and database is inconsistent, and the user won’t see the latest price, which will cause problems.

The solution to write caching will depend on your application’s needs. Write-back and write-through caching are some options. Check out this excellent primer for more information.

Conclusion

As you’ve seen, caching can immensely speed up your application, but not without caveats. When implementing caching, it’s important to think about how often your data will be accessed and how important immediate data consistency (from the user’s perspective) is in your application.

Hopefully, this guide has shown you how to get started with Laravel caching. Make sure you check out the Laravel Cache Documentation for more information. And if you’re interested in learning more about PlanetScale’s next-level features like database branching and deploy requests, check out our documentation. You can find the final code complete with caching in this GitHub repo. Thanks for reading!

Laravel News Links