Most Common AR-15 Malfunctions and Quick Fix Guide

https://www.ammoland.com/wp-content/uploads/2024/09/common-ar15-malfunctions-500×375.jpg

the most common ar-15 malfunctions
Most Common AR-15 Malfunctions and Quick Fix Guide

The AR-15 platform, known for its reliability and versatility, is popular among shooters for various applications, from sport shooting to home defense. However, like any mechanical system, it is not immune to malfunctions. Whether at the range or in a critical situation, experiencing a malfunction can be frustrating and, at times, dangerous if not handled properly. Understanding the most common issues and knowing how to quickly and effectively clear them is essential for any AR-15 owner.

In this article, we’ll explore the most common AR-15 malfunctions, such as failure to feed, failure to eject, and double feeds, along with practical tips on addressing each one. These troubleshooting techniques can help ensure your rifle operates smoothly, reducing downtime and keeping you target focused. Always remember to prioritize safety when diagnosing and clearing any firearm malfunction.

Live Inventory Price Checker


Lead Star Arms Barrage 16" .223/5.56 AR-15 Rifle with 17" Ravage Handguard, Black
Palmetto State Armory
$
1259.99


$
999.99


Lead Star Arms Barrage 16" .223/5.56 AR-15 Rifle with 17" Ravage Handguard, Black
Palmetto State Armory
$
1259.99


$
999.99


Colt .223 Rem/5.56 AR-15 Rifle – AR15A4
Palmetto State Armory
$
1374.99


$
1019.99


Colt .223 Rem/5.56 AR-15 Rifle – AR15A4
Palmetto State Armory
$
1374.99


$
1019.99

Faxon AR-15 reconfigured to resemble an M16-A4.
(Photo: Scott Witner)

Safety First

Before diving into specific malfunctions, it’s important to emphasize the need for safety. If your AR-15 doesn’t fire as expected, remove your finger from the trigger and ensure the firearm is pointed in a safe direction. Avoid attempting to force the weapon to function. Instead, take a moment to assess the situation calmly. With experience, diagnosing and clearing malfunctions will become second nature, but taking it slow and steady is the safest approach for now.

Before we get into the list of the most common malfunctions, check out the following video by Pat McNamara on handling the most common rifle malfunctions. He breaks it down into an easy-to-understand format that everyone can understand.

Failure to Feed (FTF)

Failure to Feed (FTF) is one of the most common malfunctions encountered by AR-15 users. It occurs when a round from the magazine fails to load into the chamber. This malfunction can happen unexpectedly, whether it’s the first shot of the day or midway through a magazine. The good news is that most failure-to-feed issues are straightforward to diagnose and resolve.

Quick Fix:

Tap, Rack, Reassess: Tap the magazine to ensure it’s seated, rack the charging handle to chamber a round, and reassess the rifle’s readiness to fire. If the problem persists, switch out the magazine and check for worn-out springs or bent feed lips.

Preventative Tip: Regularly inspect your magazines. For reliable performance, consider using trusted options like Magpul Gen 3 PMAGs or D&H metal magazines. Why these? The D&H mags don’t just stand up to the challenge; they’re built for it, with anti-tilt followers and a gray Teflon finish that withstands temperature changes and environmental challenges like a champ.

AR-15 magazine malfunctions
(Photo: Scott Witner – Magpul PMAG (Left) D&H Metal Mags (Right)

As a Marine infantryman, I’ve carried the M16/M4 across the globe and fired thousands of rounds through them. This experience hasn’t just made me a better shooter; it’s shown me firsthand how often gear can fail, especially magazines. Most malfunctions? They came down to issues with the mags—worn out from use, bent feed lips, damaged followers, or springs that just couldn’t cut it anymore. The fix was usually simple: swap out the faulty magazine. More often than not, that was all it took to get back in action.

Failure to Eject/Extract (FTE)

Failure to Eject (FTE), also known as a “stovepipe” malfunction, occurs when the empty cartridge case of a fired round fails to exit the chamber and gets stuck, usually protruding from the ejection port. Similarly, a Failure to Extract happens when the bolt successfully extracts the spent casing from the chamber but fails to eject it completely, leaving it trapped in the rifle. Both types of malfunctions prevent the next round from being chambered.

Quick Fix:

Immediate Action: Lock the bolt to the rear, drop the magazine, and tilt the rifle to shake out the casing. If stuck, use a cleaning rod to push it out from the muzzle.

Preventative Tip: Regularly clean your bolt carrier group and chamber to prevent carbon buildup. Ensure the extractor and ejector springs are in good condition.

Failure to Fire (FTF)

Failure to Fire (FTF) occurs when the shooter pulls the trigger, but instead of the expected “bang,” there is only a disappointing “click.” This malfunction can be caused by various factors, ranging from ammunition issues to mechanical problems within the rifle. This includes rounds with improperly seated bullets, damaged casings, or bad primers.

Understanding the root causes of FTF and how to address them can save time and prevent unnecessary frustration at the range or in a critical situation.

Quick Fix:

Eject the round and check the primer for a light or absent strike.

Reload and chamber a new round. If the rifle still doesn’t fire, inspect the bolt and firing pin for damage or dirt buildup.

Preventative Tip: Use quality ammunition and keep your rifle clean and lubricated to ensure reliable firing.

Over-Gassed and Under-Gassed Rifles

Whether your AR-15 is over- or under-gassed, gas system issues can lead to a range of malfunctions that affect your rifle’s reliability and performance. Understanding the symptoms and causes of each condition is crucial for diagnosing and resolving related malfunctions effectively.

Over-gassed symptoms: Harsh recoil and failure to eject properly.

Under-gassed symptoms: Failure to lock the bolt back or weak ejection.

Quick Fixes:

Over-Gassed: Install an adjustable gas block or use heavier buffers and springs to slow down the cycling.

Under-Gassed: Check gas block alignment and use higher-quality ammunition. You may also need to switch to a lighter buffer and spring.

Preventative Tip: Keep your gas system clean and consider using an adjustable gas block to fine-tune the system for your ammo and shooting conditions.

Double Feeds

A double feed occurs when two rounds attempt to enter the chamber simultaneously, causing a jam. This usually happens when a live round is stuck behind a previously fired round or its empty casing. Faulty magazines, weak springs, or extractor and ejector failures can cause double feeds.

Quick Fix:

Drop the magazine, lock the bolt to the rear, and use your fingers or a tool to remove the obstructing rounds. After clearing the jam, insert a fresh magazine and cycle the bolt.

Preventative Tip: Ensure your magazine springs are strong and avoid overloading your magazines to reduce tension-related failures.

Bolt Override

A bolt override is a rare but serious malfunction where a live round or spent casing gets stuck above the bolt and below the charging handle. This type of jam can be particularly challenging to clear.

Quick Fix:

Drop the magazine, pull the charging handle back, and lock the bolt to the rear. While keeping pressure on the charging handle, strike the butt of the rifle on a hard surface to dislodge the obstruction.

Preventative Tip: Ensure your ejector and extractor are functioning properly and keep your rifle clean to avoid buildup that could lead to a bolt override.

Stovepipe Malfunction

A stovepipe malfunction, named for how the spent casing sticks vertically out of the ejection port like a stovepipe, occurs when the empty casing fails to fully clear the rifle during ejection. This can disrupt the cycle of operations and prevent the next round from being chambered. Although stovepipes are relatively easy to fix, repeated occurrences can indicate underlying issues that need to be addressed.

Quick Fix:

To eject the casing, perform the “tap, rack, reassess” drill. If it’s still stuck, manually lock the bolt to the rear and clear the obstruction.

Preventative Tip: Keep your rifle clean, especially the bolt carrier group, and ensure your ejector functions correctly. If this happens frequently, consider upgrading your ejector spring.

Conclusion

Experiencing these AR-15 malfunctions can be frustrating, but understanding the most common issues and how to address them will help you become a more proficient and confident shooter. Regular maintenance, proper cleaning, and using quality components are key to minimizing these malfunctions.

From failure to feed to stovepipe malfunctions, each issue has specific causes and solutions. By familiarizing yourself with these troubleshooting techniques, you can quickly diagnose and clear malfunctions, ensuring your rifle remains functional.


About Scott Witner

Scott Witner is a former Marine Corps Infantryman with 2ndBn/8th Marines. He completed training in desert warfare at the Marine Air Ground Combat Center, Mountain Warfare and survival at the Mountain Warfare Training Center, the South Korean Mountain Warfare School in Pohang, and the Jungle Warfare school in the jungles of Okinawa, Japan. He now enjoys recreational shooting, trail running, hiking, functional fitness, and working on his truck. Scott resides in Northeastern Ohio.

Scott Witner

AmmoLand Shooting Sports News

Longer Battery, Better Tracking, Improved Fit: Halo Collar 4 Review

https://s3.us-east-1.amazonaws.com/images.gearjunkie.com/uploads/2024/09/IMG_R_0098.jpg

(Photo/Rachelle Schrute)

The peace of mind that comes with knowing your dog is safe is almost invaluable. I should know. I currently have 11 dogs. Each of them has some kind of collar that best suits their sport, personality, and temperament.

I’ve not hidden my love of Halo GPS dog collars. I’ve used just about every major “wireless fence” style dog collar on the market, and the Halo collars have yet to let me down. Where other collars have failed and left me searching for one of my bird dogs for several days, the Halo Collars have stepped up and always filled the role of reliable, consistent, and user-friendly.

When I heard the Halo Collar 4 was coming out, I assumed it would be much the same when I agreed to test it. I was wrong. Not only does it sport a smaller frame and hinged component, making it far more comfortable for a pup, but it’s also compatible with dogs half the size of its predecessor (from a 20-pound minimum size down to 20-pound pups).

The biggest claim is the jump in battery life. You can go ahead and color me skeptical when a brand makes bold battery life claims. So, did it measure down and battery up as much as the brand claims?

In short: Skepticism be damned. The Halo Collar 4 ($599) outperforms its predecessor in every way, which is a tough feat to conquer. The battery life is wild and, in my tests, actually goes above and beyond what the company claims.

Halo Collar 4 Review

Specs

  • Dual-frequency GPS collar
  • Fits dogs 10 lbs. and up with neck sizes from 8" up to 30.5"
  • Smaller, hinged fit
  • 30+ battery life
  • (New) Midnight Blue, Graphite, Orchid, and Sunburst colors.

Pros

  • Incredible jump in battery life

  • Better fit for more dogs

  • Very accurate real-time location

Cons

  • Another new, collar-specific charger


Rachelle Schrute

What Halo Has to Say About the Newest Addition to the Lineup

If we’re going to start anywhere, let’s start with cofounder Cesar Millan. I want you to picture the following quote in his voice. It makes it better, I promise.

“Halo Collar 4 allows pet parents to set rules, boundaries and limitations while creating a backyard everywhere they go. You can now provide trust, respect and love to your dog knowing they are safe wherever they go.” 

— Halo Cofounder Cesar Millan

Cesar Millan
(Photo/Halo)

The Halo Collar 4 promises a lot. I’m going to do something I rarely do and copy the intro to the press release here verbatim (with a few Oxford commas added because I have editorial integrity).

Halo, the most advanced GPS dog fence ever created, is launching the Halo Collar 4, the first collar designed to fit big and small dogs, giving pet parents the ability to create a “backyard” everywhere they go. It is the first and only dual-frequency GPS dog fence for unrivaled accuracy that combines data from L1 and L5 GPS bands for the most accurate location that is not impacted by obstacles, even in urban or bad signal areas. 

Halo Collar 4 also offers the perfect fit for big and small dogs with a tailoring system that lets you custom fit the collar to your dog’s exact neck size from 8 inches to 30.5 inches. The updated rendition includes 25% more battery life for 30+ hours between charges, a smaller and lighter all-day fit, and comes in a new Midnight Blue color, as well as updated Graphite, Orchid, and Sunburst colors.

Those are some hefty claims that I was borderline excited to bust.

Testing the Halo Collar 4

Dogs in the bed of a truck in the mountains
Bird dogs at elk camp too interested in birds; (photo/Rachelle Schrute)

The Trainee

The thing about bird dogs from a strong hunting line is this: when bird season rolls around, a young bird dog can be almost impossible to keep contained when birds are about. My youngest Brittany is that dog. At a year and a half old, she knows her duty is to hunt ’em up. She does not, however, practice much restraint when she isn’t supposed to hunt ’em up. Known for having boundless energy, she measures up in all the best and worst ways that her breed has to offer.

Enter the true challenge for the Halo Collar 4. Even when faced with rooster pheasants at the edge of her perimeter, the Halo collars have kept her contained without the need for static shock or human intervention. She’s learned her tones and learned that it’s only when the collar comes off and the shotgun comes out that she can take to the field.

Battery Life to the Moon

Halo Collar Comparison
The Halo Collar 3 (Yellow) and the Halo Collar 4 (blue) after being dirtied and covered by dog hair, as they should be; (photo/Rachelle Schrute)

After testing two previous version of the Halo collars, I wasn’t sure I’d see much benefit with the newest iteration. And then the battery life jumped up and smacked me in the face.

I run the Halo Collar 2 and Halo Collar 3 on another Brittany and a German shorthair. Both those collars give me a day of battery life. When I say a day, I mean a daylight day. Depending on how rowdy the pups get, I see anywhere from 8 to 12 hours of consistent battery life. That means they are contained for the work day and a bit after. Each night, the collars get plugged in when the pups get tucked into bed.

The Halo Collar 4 has run for 2 full days with no charge and held battery life the entire time. Yes, while at home, it still gets plugged in every night. However, this means a weekend away in the mountains requires no additional draw on the power banks I rely on. That leap in battery life is huge for those who overnight sans power in the great outdoors.

What the Halo Collar 4 Does Well

Halo Collar 4
The new Midnight Blue color option; (photo/Halo)

Everything it claims to. If you need a reliable GPS dog collar to keep your pup contained without fences, this collar will do it and do it well. If you have a pup that is too small to wear most GPS collars, this one might be the ticket.

I love being able to sit at my desk and look at the exact location of my pups on my phone. They don’t have to be penned up when I’m not looking. They can roam and play and be dogs, all while I know they are safe and secure. I’m not a fan of putting up fences for a heap of reasons, and this allows me to keep the landscape natural and my dogs safe.

The App

Halo App

The Halo Collar App is another huge win for Halo. I’ve used other digital-fence-style collars with apps that made me want to throw my phone out the window. The Halo app is user-friendly, intuitive, clean, and simple to use. I can open my phone, see where my dogs are, and even whistle at them to come home. The app is top-notch in the world of GPS collars.

It also has a full dog training module taught by none other than Cesar Millan himself.

Always On

This is a big one. If your collar dies and you stick it on the charger, it turns itself back on. You don’t need to hold the power button for 30 seconds, rub your belly six times, and spin in a complete circle to get the collar to turn on and connect to the app. That might seem silly, but I’ve used other collars that are a pain in the royal arse to get reconnected to your phone, and I was never certain whether the collar was even on.

The Halo Collar 4 (and its previous versions) turns itself on and automatically connects to the app, ensuring immediate protection for your pup by just grabbing it off the charger and snapping it on. It’s grab-and-go protection that has never let me down.

Where’s the Downside?

Halo Collar 4
The hinged collar is rad. Another new charger is less rad; (photo/Halo)

You could say that they’re expensive, but they really aren’t. The Halo Collar 4 is at or below the cost of almost any other big-name GPS collar at $599.

The Charger

What you could complain about is the charger, but that’s only if you have former versions of the collar. I have three different versions, and each one has a different charger. That is frustrating, but I do get it. The newer versions likely require a bit more oomph, so they likely require a heftier charger.

That being said, a universal USB-C charger would be a huge perk, especially if you’re on the go and don’t have your collar-specific charger handy. Only my oldest Halo Collar offers that option.

A Little Lag

This is one that I guess can be expected. Occasionally, depending on weather or tree cover, you might experience a little lag in GPS connection. I always try to open my app when I send the pups outside, just to make sure they’re connected and covered. That being said, the lag is absolutely minimal, particularly when compared to other GPS collars.

Who Should Buy the Halo Collar 4?

Halo Collar 4
For little and big pups; (photo/Halo)

Anyone interested in knowing where their canine companion is without going to the window or walking outside should consider the Halo Collar 4. This collar is perfect for anyone who lives near a busy road or can’t put up a fence. It’s the solution for weekend warriors who need to keep their pup at camp and out of the far-reaching mountains.

To be honest, I’m not sure who the Halo Collar 4 wouldn’t be good for. If you have a dog that weighs 10 pounds or more, you would benefit from adding it to your pup’s accessories. Period. End of story. They rock.

One of the other perks is that I bet the Halo Collar 3 is about to go on sale. So … you know, getcha one of those, too.

If you can’t tell, I stinkin’ love mine.

The post Longer Battery, Better Tracking, Improved Fit: Halo Collar 4 Review appeared first on GearJunkie.

GearJunkie

Prevent and Detect Rapid Fire Password Attacks on MySQL

Using “failed login” policies, dbas can prevent brute force rapid fire attacks on MySQL user’s passwords. This uses a technique know as “login throttling”. This method affectively thwarts these “rapid fire” login attempt attacks by increasing delays for each failed attempt. These policies are simple and straightforward to put in place and define. Enabling defense and detection of rapid fire and other password attacks.Planet MySQL

How to Enable, Configure, and Use MySQL Query Logging

In this article, we will address questions such as the purpose of query logging in MySQL, why it is important, how to enable and configure it, and more. You’ll find a detailed guide on how to use mysqldumpslow to analyze slow query logs, along with tips on harnessing convenient GUI tools like dbForge Studio for MySQL to your advantage.

The post How to Enable, Configure, and Use MySQL Query Logging appeared first on Devart Blog.

Planet MySQL

Triple Apple Charger/US Passport Changes/Designer Cities

A weekly newsletter with four quick bites, edited by Tim Leffel, author of A Better Life for Half the Price and The World’s Cheapest Destinations. See past editions here, where your like-minded friends can subscribe and join you.

Triple Travel Charger for Apple Devices

If you’re all-in on Apple products, you might like this 3-in-1 travel charger a reader recommended for your iPhone, watch, and Airpods. The folding magnetic charger is smaller than a phone but can charge up all three of these fast-fading devices every night so you can start fresh in the morning. Selling for $60 now at Amazon. (Thanks to reader Jim from the SpanishAndGo podcast, which I recommend by the way if you’re an intermediate learner.)

Two U.S. Passport Developments

Good news for U.S. passport holders this week. First of all, the State Department is leaping into the modern age and you can now renew your passport online after a successful beta text. Just don’t expect it to be any faster, they warn. Also, Google announced that it’s in beta tests to create a digital ID from your passport that you’ll be able to use at TSA checkpoints. They’re also adding driver’s licenses for many states and commuter cards for public transportation.

New UK Entry Fee

It’ll soon cost you the equivalent of a few pub pints to enter the UK—unless you’re Irish. Most countries will have to apply for and pay a fee of £10. For most travelers that begins in November, but for Europeans it will roll out in the spring. You’ll even have to cough up the fee for your lap baby as apparently this fee to fund enhanced security is required for them as well. This is separate from the upcoming ETIAS €7 fee to enter the EU, so you’ll pay twice if you’re going to both. See the details here.

Cities That Inspire Designers

Where do interior designers like to go when they’re looking for inspiration? This article from House Beautiful runs down 12 places that the people picking out sofas and curtains called out when asked. Some are a bit puzzling to me, but I’ve certainly seen hints of other named spots in Morocco, Colombia, Turkey, and Italy in restaurants and hotels in other places.

Cool Tools

The History of PKM, the Most Common Machine Gun In the World (Part 1)

https://cdn-fastly.thefirearmblog.com/media/2024/09/16/10061/the-history-of-pkm-the-most-common-machine-gun-in-the-world-part-1.jpg?size=720×845&nocrop=1

Everyone knows AK-47. It is everywhere: movies, books, crime statistics. Interestingly enough, those who spend some time in the warzone often have stronger feelings towards another Kalashnikov creation – the PK/PKM belt-fed machine gun.

Some say that PK is the best weapon Kalashnikov ever created. While AK was developed at the very beginning of his career, PK was created when Kalashnikov had plenty of experience.

Millions of those machine guns are used all over the world, US special forces requested American companies to produce those guns multiple times, and some experts call it “the best general purpose machine gun”.

However, few people know that it was created almost by accident. There are many great articles on AK history, but there is almost nothing published in English about the PK development, and hopefully, this article can fix that.

One of many PKMs the author inspected and repaired in Afghanistan

How it all started

The summer of 1959 was a busy time for Mihail Kalashnikov. The new family of weapons he designed, which included AKM and RPK light machine guns, was just getting into production. He had to prove for the second time in his career that his rifle was the best.

First, his AK 47 won the competition in 1949, and ten years later his other creation, AKM bested all rivals and now was destined to become the new service rifle of the Soviet Army and most Warsaw Pact countries.

Kalashnikov hadn’t had a vacation in 4 years. That summer there was finally an opportunity to celebrate, and it was all more convenient that his old friend visited him in the city of Izhevsk.

Vladimir Deikin and Mihail Kalashnikov

The old friend was army officer Vladimir Deikin, who was one of the people who made AK happen. The officer of GRAU, the military department responsible for procurement of new weaponry, he supported Kalashnikov all the way through the development of the original AK rifle, ruthlessly crushing bureaucracy and red tape that got in the way of a young weapon design engineer.

As the years went by, a young and shy Kalashnikov became the most respected weapon designer in the Soviet Union, and Vladimir Deikin became a colonel, rising to the top of the career ladder.

That summer two friends who have been through a lot could finally enjoy their life. They took a boat and went fishing, invited friends from the factory, and spent the weekend in a cabin on the lake, talking about guns and cooking fish they caught.

Before leaving, Vladimir Deikin nonchalantly shared some news: “This guy Nikitin at the factory in Tula is developing GPMG (general purpose machine gun). The trials are almost over, it adheres to the requirements… But in GRAU we think it is a little too complicated. The army needs something more simple”.

Prototype of the Nikitin GPMG

He didn’t ask Kalashnikov to get involved. He never asked for help. But he knew his old friend and realized, Kalashnikov won’t just leave it alone. Now, after his friend left, Kalashnikov had a whole bunch of questions.

Why wasn’t I asked to develop this new GPMG? Why don’t they trust me? Am I in trouble? How complicated is too complicated? Will they ask me to redesign this gun once it finishes trials? Or is it the end of my career?

The brainstorming

Kalashnikov decided that he must do something about it. He already had a team of engineers and enough authority to build a machine gun from scratch without asking permission.

There was no money allocated for this project, but he could pull some strings and use money from his other projects to finance the ammo and all the prototype building.

Prototype of the PK. The machine gun is from the collection of the Artillery Museum in Saint Petersburg.

He became obsessed with his new machine gun and completed the first sketches in just ten days. However, drawings alone are no good, you need to make blueprints, which Kalashnikov couldn’t really do – he was never formally educated and always relied on someone else to make blueprints.

In this case, engineer Krupin was tasked with creating proper blueprints, and the entire team got on with the project. The rival machine gun from Tula was already undergoing troop trials, the Ministry of Industry never asked for another contender, but Kalashnikov decided that he would deal with that another day.

The obsession Kalashnikov had was contagious, engineers were staying at work until 5 in the morning, and within weeks they started making the first parts of the prototype.

Milled receiver of the PK prototype. The machine gun is from the collection of the Artillery Museum in Saint Petersburg.

Often, there was no time to make proper blueprints, so engineers just winged it, making parts on the lathe and milling machine relying solely on their imagination and some sketches.

Within a month, the first prototype of PKM was ready. Now Kalashnikov just had to convince the entire Soviet military-industrial complex that his crude prototype was better than a machine gun that already passed all the trials and ticked all the boxes. How did he manage to do that? That is the story for Part 2 of this article.

The Firearm Blog

Understanding MySQL Indexes: Types, Benefits, and Best Practices

https://www.percona.com/blog/wp-content/uploads/2024/06/Understanding-MySQL-Indexes-200×112.jpgWhen it comes to MySQL databases, performance is everything. As more activities move online and data volumes grow exponentially, ensuring efficient data retrieval and query execution becomes crucial. Database indexing plays a significant role in this by providing powerful tools to optimize operations in MySQL. Without an index, MySQL must perform a full table scan, […]Percona Database Performance Blog

These Are My Favorite Google Docs Invoice Templates

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2024/09/tax-professional-with-a-digital-invoice.jpg

Google Docs templates make it easy to start creating resumes, letters, brochures, reports, and project proposals, but there is no built-in template for making invoices in Google Docs.

MAKEUSEOF VIDEO OF THE DAY
SCROLL TO CONTINUE WITH CONTENT

So, what do you do when you need to create an invoice? You could painstakingly create one from scratch for every client or use one of these free, customizable invoice templates available for download.

Square is an end-to-end payment processor that can be used to accept payments from clients as a freelancer. It offers a free, client-ready invoice template that can be downloaded in various formats: Word, Excel, and PDF.

You will need to fill in the details required: your business information (name, location, email address, and phone number), the customer’s information, due date and amount, payment terms, and the job description. Replace the logo placeholder with a suitable image, and delete the Square Invoices footer. List each important line item in the breakdown table. You can duplicate the borderline in the breakdown table and add more items as needed.

The Square invoice template isn’t directly available for Google Docs, but you can download the Word document and open it in Google Docs for editing and customization.

Wave is popular for its invoicing and accounting software, but it also offers a free Google Docs invoice template that any freelancer or small business owner can tailor to send to their clients. There are up to five different invoice templates available in Doc, Sheets, PDF, and Excel. All templates are simple, attractive, and professional. They can be customized to fit your brand image and business clients.

After selecting the template you prefer, you can proceed to insert your business name, project details, and other information. It doesn’t include a logo placeholder, but you can still place one in the header or the background of the document. There is a Notes section at the bottom for additional details such as payment terms, terms of service, and probably, a warm, appreciative message to the client.

Creating an invoice template reduces the work you have to do each time since you can incorporate the logo and other non-changing information in the template itself. Also, it will make it much easier to make templates for more complicated documents. By following our guide to creating an invoice template in Google Docs, you will be able to create simple invoices that you can send to your clients with little editing.

Invoice Simple is a freemium invoicing software available on mobile and web platforms. The company has a collection of free Google Docs and Sheets invoice templates. The spreadsheet versions are recommended for download since they come with built-in formulas and are easier to customize.

You can choose an invoice template from the collection, click Google Docs under the image, and select Make a copy in the next window. You can then proceed to replace the placeholders and enter the requisite information. The Invoice Simple template includes a Ship to section for businesses with a physical product. Make sure to omit this section if you don’t need it.

The GooDocs website features thousands of free templates for Google Docs, Google Slides, and Google Sheets. You can download up to five templates for free without creating an account. On GooDocs, there are several invoice templates to choose from, with categories like consulting, contracting, freelance, medical, wedding, rental, and restaurant. With the myriad choices available, you will be able to find an invoice template that suits your business needs.

Once you find the one you like, you can select Edit in Google Docs from the sidebar options. You should switch the colors, fonts, and other design elements to better match your business’ branding. Your logo should be prominently displayed in the invoice’s header.

With a little bit of editing, you can turn any Google Docs invoice template into a professional, client-ready invoice document that makes a great impression.

MakeUseOf

MySql Explain with Tobias Petry

https://picperf.io/https://laravelnews.s3.amazonaws.com/featured-images/Tobias Petry on MySQL.png

This week, we welcome Tobias Petry to the Laravel Creator Series show to discuss his journey into database optimization, the development of his MySQL Explain tool, and the acquisition of the domain mysqlexplain.com. Tobias also shares insights about his other projects, including Stack Bricks, a tool for managing different database versions, and his contributions to the Laravel Debug Bar.

➡️ Save 10% on his Indexing Beyond the Basics book and video package with the coupon code LARAVELNEWS

Show Links


The post MySql Explain with Tobias Petry appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.

Laravel News

IMPLEMENTING MULTI-TENANCY IN LARAVEL: A COMPREHENSIVE GUIDE

https://zorandev.info/storage/01J53ME8JCDTVWY15S163T4JWA.webp

Multi-tenancy in web applications refers to the architecture where a single instance of the application serves multiple customers, or ‘tenants.’ Each tenant’s data and, sometimes, specific configurations are kept isolated from others. This setup is essential in SaaS (Software as a Service) platforms where multiple businesses or organizations might use the same application.

In this guide, we’ll walk through setting up a database-per-tenant approach in Laravel, complete with code examples, detailed explanations, and the necessary console commands for creating the database itself with no need or usage of any external package.
Step 1: Setting Up Database Connections
In the config/database.php file, we define two connections:

1. ** Owner Connection**: This connection manages the information about all tenants, such as their domain and database names.
2. **Tenant Connection**: This connection dynamically switches based on the tenant currently being accessed.

Here’s how to set up these connections:

return [
    'default' => env('DB_CONNECTION', 'tenant'),

    'connections' => [
        'tenant' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => null, // Database will be set dynamically
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
        ],

        ' owner' => [
            'driver' => 'mysql',
            'host' => env(‘OWNER_DB_HOST', '127.0.0.1'),
            'port' => env(,OWNER _DB_PORT', '3306'),
            'database' => env(' OWNER _DB_DATABASE', 'landlord'),
            'username' => env(' OWNER _DB_USERNAME', 'root'),
            'password' => env(' OWNER _DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
        ],
    ],
];

Step 2: Creating the Tenant Model and Migrations
We need to create a Tenant model that uses the landlord connection. This model will manage tenant-related data such as the domain and database name.
Tenant Migration:

In the migration for the tenants table, we’ll include columns for the tenant’s name, domain, and the specific database used:

Schema::create('tenants', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('domain')->unique();
    $table->string('database');
    $table->timestamps();
});

Tenant Model:

The Tenant model should be linked to the landlord connection and include methods for configuring and using the tenant:

class Tenant extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'domain',
        'database',
    ];

    protected $connection = 'owner'; // Default connection for the owner database

    /**
     * Configure the tenant's database connection dynamically.
     */
    public function configure(): self
    {
        // Update the configuration for the tenant connection dynamically
        config([
            'database.connections.tenant.database' => $this->database,
        ]);

        // Purge the 'tenant' connection to refresh its settings
        DB::purge('tenant');

        // Clear tenant-specific cache if cache table exists
        if (Schema::hasTable('cache')) {
            $this->clearTenantCache();
        }

        return $this;
    }

    /**
     * Activate the tenant context across the application.
     */
    public function use(): self
    {
        // Set the default database connection to 'tenant'
        DB::setDefaultConnection('tenant');

        return $this;
    }

    /**
     * Clear cache specific to the tenant.
     */
    public function clearTenantCache(): void
    {
        // Get tenant-specific cache keys
        $cacheKeys = Cache::get('tenant_'.$this->id.'_keys', []);

        // Forget each cache key
        foreach ($cacheKeys as $key) {
            Cache::forget($key);
        }

        // Optionally remove the keys tracking itself
        Cache::forget('tenant_'.$this->id.'_keys');
    }

    /**
     * Add a tenant-specific cache key.
     */
    public function addCacheKey(string $key): void
    {
        // Get the current list of cache keys for the tenant
        $cacheKeys = Cache::get('tenant_'.$this->id.'_keys', []);

        // Add the new cache key
        $cacheKeys[] = $key;

        // Update the list in the cache
        Cache::put('tenant_'.$this->id.'_keys', $cacheKeys);
    }
}

Step 3: Custom Console Command for Tenant initialization 

We will create console command to initialize the owner table where all tenant database info will be stored 

class TenantInit extends Command
{
    protected $signature = 'tenants:init';
    protected $description = 'Create owner table where all domains for tenant app live';

    public function handle(): int
    {
        DB::setDefaultConnection('owner');
        $path = database_path('migrations/owner'); // Custom migration path for the owner DB
        $this->info('Running migrations from: ' . $path);

        try {
            $this->call('migrate', ['--path' => $path, '--force' => true]);
            $this->info('Migrations have been executed successfully.');
        } catch (\Exception $e) {
            $this->error('An error occurred: ' . $e->getMessage());
            return 1; // Return non-zero for failure
        }

        return 0; // Return zero for success
    }
}

Step 4: Custom Console Command for Tenant Migrations

Since each tenant has its own database, we need a way to migrate the schema for each one. Laravel’s built-in migrate command only runs migrations on the default connection, so we’ll create a custom Artisan command to handle tenant migrations.
TenantsMigrateCommand:

This command will loop through all tenants, configure the tenant’s database connection, and run migrations on each database:

class TenantsMigrateCommand extends Command

{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tenants:migrate {tenant?} {--fresh} {--seed}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create clean migration and seed for one tenant or for all tenants';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        if ($tenantId = $this->argument('tenant')) {
            $tenant = Tenant::find($tenantId);
            if ($tenant) {
                $this->migrate($tenant);
            } else {
                $this->error("Tenant with ID {$tenantId} not found.");
            }
        } else {
            Tenant::all()->each(
                fn ($tenant) => $this->migrate($tenant)
            );
        }
    }

    /**
     * Migrate the given tenant.
     */
    public function migrate(Tenant $tenant): void
    {
        $tenant->configure()->use();
        $this->line('');
        $this->line('-----------------------------------------');
        $this->info("Migrating Tenant #{$tenant->id} ({$tenant->name})");
        $this->line('-----------------------------------------');
        $options = ['--force' => true];
        if ($this->option('seed')) {
            $options['--seed'] = true;
        }
        $this->call(
            $this->option('fresh') ? 'migrate:fresh' : 'migrate',
            $options
        );
    }
}

• {tenant?}: The tenant argument is now optional. If provided, it will run migrations for the specified tenant only.
• {–fresh}: Option to run migrate:fresh, which drops all tables and re-runs all migrations.
• {–seed}: Option to seed the database after running migrations.

Step 5: Middleware for Tenant Resolution

To ensure that the correct tenant is used for each request, we’ll create middleware that identifies the tenant based on the domain and configures the application accordingly.
TenantSessionMiddleware:

class TenantSessionMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->session()->has('tenant_id')) {
            $request->session()->put('tenant_id', app('tenant')->id);
            return $next($request);
        }
        if ($request->session()->get('tenant_id') != app('tenant')->id) {
            abort(401);
        }

        return $next($request);
    }}

Step 6: Testing Multi-Tenant Applications
Testing in a multi-tenant environment requires that both the landlord and tenant databases are properly set up before each test. Here’s how you can configure your tests:

public function setUp(): void
{
    parent::setUp();

    // Migrate the owner's database and seed data
    $this->artisan('migrate', ['--database' => 'owner']);
    $this->seed(OwnerSeeder::class);

    // Loop through tenants and migrate their databases
    Tenant::all()->each(function (Tenant $tenant) {
        $tenant->configure();
        $this->artisan('migrate', ['--database' => 'tenant']);
    });
}

Step 7: Setting Up a Service Provider for Tenant Resolution

In a multi-tenant application, it’s crucial to ensure that the correct tenant context is established for each incoming request. This is where a service provider comes into play. The service provider will configure the tenant based on the request’s domain or subdomain, ensuring that the correct tenant’s database and other settings are used throughout the application lifecycle.

Creating the TenancyServiceProvider

<?php

namespace App\Providers;

use App\Models\Tenant;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;

class TenancyServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        $this->configureTenant();
        $this->configureQueue();
    }

    /**
     * Configure tenant based on the domain.
     */
    protected function configureTenant(): void
    {
        if ($this->app->runningInConsole()) {
            return;
        }

        $host = request()->getHost();
        $tenant = Tenant::whereDomain($host)->firstOrFail();
        $tenant->configure()->use();  // Set up and use tenant configuration
    }

    /**
     * Configure the queue system to be aware of tenants.
     */
    protected function configureQueue(): void
    {
        // Add tenant_id to the job payload
        Queue::createPayloadUsing(function () {
            if (app()->bound('tenant')) {
                $tenant = app()->make('tenant');

                return ['tenant_id' => $tenant->id];
            }

            return [];
        });

        // Restore tenant context when job is processing
        Event::listen(JobProcessing::class, function (JobProcessing $event) {
            $tenantId = $event->job->payload()['tenant_id'] ?? null;

            if ($tenantId) {
                $tenant = Tenant::find($tenantId);
                $tenant?->configure()->use();
            }
        });
    }
}

Expanded Explanation of Service Provider Methods
The methods you’ve shared are essential for managing tenant context both during normal HTTP requests and within Laravel’s queue system. These methods ensure that the correct tenant is always in scope, whether you’re handling web requests or processing background jobs.

Method 1: configureTenant

protected function configureTenant(): void
{
    if ($this->app->runningInConsole()) {
        return;
    }

    $host = request()->getHost();
    $tenant = Tenant::whereDomain($host)->firstOrFail();
    $tenant->configure()->use();  // Set up and use tenant configuration
}

Explanation:

Purpose: This method sets up the tenant configuration based on the incoming request’s domain and ensures that the correct tenant is used throughout the request lifecycle.

if ($this->app->runningInConsole())
{ 
   return; 
}:

This check ensures that the tenant configuration logic only runs during HTTP requests. If the application is running in the console (e.g., during migrations or other Artisan commands), the method will exit early. This is because console commands may not be associated with any particular tenant, and running tenant-specific logic could cause unintended behavior.

$host = request()->getHost();:

This retrieves the domain name from the incoming HTTP request. The domain is typically used to determine which tenant the request is for.

$tenant = Tenant::whereDomain($host)->firstOrFail();:
This line queries the tenants table to find the tenant that matches the domain name. The firstOrFail() method will throw a ModelNotFoundException if no tenant is found, which can result in a 404 error being returned to the user.

$tenant->configure()->use();:
Once the tenant is found, the configure() method sets up the database connection and other tenant-specific configurations.
The use() method then registers this tenant in the service container, making it accessible throughout the application for the duration of the request.

Method 2: configureQueue

/**
 * Configure the queue system to be aware of tenants.
 */
protected function configureQueue(): void
    {
        // Add tenant_id to the job payload
        Queue::createPayloadUsing(function () {
            if (app()->bound('tenant')) {
                $tenant = app()->make('tenant');

                return ['tenant_id' => $tenant->id];
            }

            return [];
        });

        // Restore tenant context when job is processing
        Event::listen(JobProcessing::class, function (JobProcessing $event) {
            $tenantId = $event->job->payload()['tenant_id'] ?? null;

            if ($tenantId) {
                $tenant = Tenant::find($tenantId);
                $tenant?->configure()->use();
            }
        });
    }

Explanation:
Purpose: This method ensures that Laravel’s queue system is tenant-aware. By attaching the tenant_id to the job payload, and reconfiguring the tenant context during job processing, we ensure that the job runs in the correct tenant’s context. This is particularly crucial for distributed queue systems like Redis, where workers could be shared across tenants.

Queue::createPayloadUsing():

This method hooks into the queue system to modify the job payload. The payload is essentially the data that is passed along with a job when it is queued.

if ($this->app->bound('tenant')) {:

This checks if the application has a tenant bound to the service container. If a tenant is bound, it means the current request is associated with a specific tenant.

$tenant = $this->app->make('tenant');:

This retrieves the currently bound tenant from the service container.

return ['tenant_id' => $tenant->id];:

This adds the tenant_id to the job payload, ensuring that the tenant context is passed along with the job when it is dispatched.

return [];:

If no tenant is bound, the payload remains unchanged.

Event::listen(JobProcessing::class, ...):

This listens for the JobProcessing event, which is fired just before a queued job starts processing.

$tenantId = $event->job->payload()['tenant_id'] ?? null;:

This retrieves the tenant_id from the job’s payload. If no tenant_id is found, it returns null.

$tenant = Tenant::find($tenantId);:

This finds the tenant by the tenant_id stored in the payload.

$tenant?->configure()->use();:

If a tenant is found, the configure() method sets up the tenant’s database connection, and use() registers this tenant as the current tenant for the job’s processing context.
You can create a service provider that handles the tenant resolution and configuration. This service provider will hook into Laravel’s bootstrapping process and set up the tenant context at the beginning of each request.
Conclusion
Implementing multi-tenancy in Laravel using a database-per-tenant approach offers strong data isolation and scalability. The steps outlined in this guide provide a complete framework for setting up multi-tenancy, handling migrations, and ensuring that your application uses the correct database for each tenant.

Pros:

• Data Isolation: Each tenant’s data is completely separated, ensuring strong data isolation.
• Scalability: This approach allows easy scaling by adding new databases for new tenants.
• Security: By isolating each tenant’s data in separate databases, the risk of data leakage between tenants is minimized.
• Cache Efficiency: The use of tenant-specific cache keys ensures that only tenant-relevant cached data is cleared, improving performance.
• Queue Robustness: Tenant context is preserved in queues, even in distributed environments, preventing cross-tenant data leakage in background tasks.

Cons:

• Complexity: Setting up and managing multiple databases adds complexity to the application architecture.
• Resource Overhead: Maintaining separate databases for each tenant requires more infrastructure resources.
• Backup Complexity: Managing backups across multiple databases can be challenging, especially when scaling to hundreds or thousands of tenants.
• Migration Overhead: Running migrations for each tenant adds additional overhead compared to a single-database architecture.
• By following this approach, you can build robust, scalable multi-tenant applications in Laravel.

the code example can be locale at  :https://github.com/KalimeroMK/multitenant

Laravel News Links