Skip to content

Instantly share code, notes, and snippets.

View Sairahcaz's full-sized avatar
🏃

Zacharias Creutznacher Sairahcaz

🏃
View GitHub Profile
@Sairahcaz
Sairahcaz / laravel-eloquent-best-practices.md
Created July 6, 2026 12:29
Eloquent & Laravel Best Practices

Eloquent & Laravel Best Practices

Prefer Laravel's expressive, model-aware APIs over manual ID plumbing. Passing models instead of raw IDs is safer (correct key resolution, route model binding) and reads better. Each section shows the pattern to avoid and the one to use.

Routing

Pass the model itself to route(), not its key. Laravel resolves thea route key automatically (and respects custom route keys).

// Avoid
<?php
// if you wanna use defer in a package where it may only be optional
// or you don't know or want to mess with if defer is already supported
// also swoole compatible if you get this error:
// Symfony\Component\ErrorHandler\Error\FatalError: Uncaught Swoole\Error: API must be called in the coroutine
if (! function_exists('safeDefer')) {
/**
# SETUP #
DOMAIN=example.com
PROJECT_REPO="git@github.com:example.com/app.git"
AMOUNT_KEEP_RELEASES=5
RELEASE_NAME=$(date +%s--%Y_%m_%d--%H_%M_%S)
RELEASES_DIRECTORY=~/$DOMAIN/releases
DEPLOYMENT_DIRECTORY=$RELEASES_DIRECTORY/$RELEASE_NAME
# stop script on error signal (-e) and undefined variables (-u)
#!/bin/sh
# creates app/Http/Requests/StorePersonRequest.php (store request is the default)
php artisan schema:generate-rules persons --create-request
# creates/overwrites app/Http/Requests/StorePersonRequest.php
php artisan schema:generate-rules persons --create-request --force
# creates app/Http/Requests/UpdatePersonRequest.php
php artisan schema:generate-rules persons --create-request --file UpdatePersonRequest
<?php
Schema::create('persons', function (Blueprint $table) {
$table->id();
$table->string('first_name', 100);
$table->string('last_name', 100);
$table->string('email');
$table->foreignId('address_id')->constrained();
$table->text('bio')->nullable();
$table->enum('gender', ['m', 'f', 'd']);
@Sairahcaz
Sairahcaz / laravel.conf
Last active September 12, 2023 07:49
Default Laravel Nginx Config
server {
listen 80;
listen [::]:80;
server_name example-app.test;
root /home/zacha/code/example-app/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
<?php
use LaracraftTech\LaravelDateScopes\DateScopes;
class Transaction extends Model
{
use DateScopes;
}
// Usage
<?php
/**
* A php 8 like match expression for php 7
*
* @param $value
* @param array $expressionArray
* @return mixed
* @throws Exception
*/
<?php
/*
* ==================
* For Pest - Pest.php
* ==================
*/
use LaracraftTech\LaravelUsefulTraits\RefreshDatabaseFast;
<?php
use LaracraftTech\LaravelUsefulTraits\UsefulScopes;
$class = new class extends Model
{
use UsefulScopes;
protected $timestamps = true;
protected $table = 'scope_tests';