Enjoy these free Code Nuggets?

Your support helps us create more high-quality content and unlocks exclusive premium nuggets via a personal activation link.

Support Our Work & Get Exclusive Access
🤖 New — AI Training

Learn to code with AI, not just about it.

Beyond free snippets, we run hands-on training in AI-assisted coding — teaching developers, teams and beginners how to build real software faster using modern AI tools. You bring the ideas; we show you how to ship them with an AI pair-programmer at your side.

  • ✔ Prompting & pairing with AI coding assistants to write, debug and refactor real code
  • ✔ Turning plain-English ideas into working apps, scripts and automations
  • ✔ Reviewing AI output safely — spotting bugs, security gaps and hallucinations
  • ✔ Live cohorts, team workshops and 1-on-1 mentoring — remote or on-site in Kenya
ai-pair-session.md

# You describe it…

"Build me a booking form that emails the client."

# …the AI drafts it…

▸ generating form + mailer…

â–¸ 24 lines written, 0 errors

# …and we teach you to lead it.

✱ You stay the engineer. AI is the tool.

All Code Nuggets

41 nuggets found

Offloading Slow Work with Laravel Queues (Premium)

Sending email, resizing images or calling third-party APIs inside a web request makes users wait. Push that work onto a queue and the response returns instantly while a worker handles...

// app/Jobs/SendWelcomeEmail.php
class SendWelcomeEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public User $user) {}

    public function handle(): void
    {
        Mail::to($this->user->email)->send(new Welc...

Validating Input Cleanly with Form Requests (Premium)

Stuffing validation rules into a controller makes it noisy. A Form Request moves rules, authorization and custom messages into their own class, and Laravel auto-validates before the controller method even...

// php artisan make:request StorePostRequest
class StorePostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Post::class);
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string...

Shaping JSON Responses with Eloquent API Resources (Premium)

Returning a raw model leaks every column and couples your API to your schema. An API Resource is a transformation layer: you decide exactly which fields ship, rename them, and...

// php artisan make:resource PostResource
class PostResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id'         => $this->id,
            'title'      => $this->title,
            'excerpt'    => Str::limit(strip_tags($this->body), 140...

Reusable Query Logic with Eloquent Scopes (Premium)

When the same where clauses appear all over your app, wrap them in a query scope. Scopes read like plain English and keep filtering rules in one place.

class Post extends Model
{
    // Local scopes: prefix with "scope"
    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at')
                     ->where('published_at', '<=', now());
    }

    public function scopeSearch($query, ?string $term)
    {...

Thinner Views with Django Class-Based Views (Premium)

Django python

Most list and detail pages follow the same pattern: fetch a queryset, paginate, render a template. Django's generic class-based views hand you that for free, so a full listing page...

from django.views.generic import ListView, DetailView
from .models import Article

class ArticleList(ListView):
    model = Article
    paginate_by = 10
    context_object_name = "articles"

    def get_queryset(self):
        qs = super().get_queryset().filter(is_published=True)
        if q := sel...

Encapsulating Queries in a Custom Django Manager (Premium)

Django python

Sprinkling filter(is_published=True) across your codebase invites bugs. A custom manager gives your model expressive, reusable query methods like Article.objects.published().

from django.db import models
from django.utils import timezone

class ArticleQuerySet(models.QuerySet):
    def published(self):
        return self.filter(is_published=True, published_at__lte=timezone.now())

    def by_author(self, user):
        return self.filter(author=user)

class Article(mode...

Reacting to Model Events with Django Signals (Premium)

Django python

Need a profile created automatically whenever a user signs up? Signals let you run code in response to model events without cluttering your save logic.

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from .models import Profile

User = get_user_model()

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:...

Cleaner Data Objects with Python dataclasses (Premium)

Python python

Writing __init__, __repr__ and __eq__ by hand is tedious. A @dataclass generates them for you, with type hints, defaults and immutability baked in.

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Money:
    amount: int          # store minor units (cents) to avoid float errors
    currency: str = "KES"

    def __post_init__(self):
        if self.amount < 0:
            raise ValueError("amount cannot be neg...

Concurrent HTTP Requests with asyncio and httpx (Premium)

Python python

Fetching 50 URLs one after another is painfully slow. With asyncio and httpx you can fire them concurrently and gather the results, turning minutes into seconds.

import asyncio
import httpx

async def fetch(client, url):
    r = await client.get(url, timeout=10)
    r.raise_for_status()
    return url, len(r.content)

async def main(urls):
    async with httpx.AsyncClient() as client:
        tasks = [fetch(client, u) for u in urls]
        return await asyn...