Syntax
<?php
declare(strict_types=1);SCAN / COPY / KEEP MOVING
Compact syntax. Open a title for context and pitfalls.
<?php
declare(strict_types=1);$names = array_map(fn ($user) => $user["name"], $users);$active = array_values(array_filter($users, fn ($u) => $u["active"]));
usort($active, fn ($a, $b) => $a["name"] <=> $b["name"]);class User
{
public function __construct(public string $name) {}
}interface PaymentGateway
{
public function charge(int $amount): bool;
}public static function fromCents(int $cents): self {}try {
// operation
} catch (Throwable $e) {
// handle or rethrow
}namespace App\Services;
use App\Models\Order;$apply = function (int $value) use ($fee): int { return $value + $fee; };$name = $input["name"] ?? "Guest";
$city = $user?->address?->city;$label = match ($status) {
"paid" => "Settled",
"pending" => "Awaiting payment",
default => "Unknown",
};count($items);
in_array($role, $allowed, true);
array_column($users, "id");
json_encode($data, JSON_THROW_ON_ERROR);Route::get("/orders/{order}", [OrderController::class, "show"]);public function show(Order $order): JsonResponse {}public function authorize(): bool {}
public function rules(): array {}$data = $request->validate(["email" => "required|email|max:254"]);class Order extends Model { protected $fillable = ["reference", "total_cents"]; }$order = Order::findOrFail($id);
$order->save();
$order->delete();public function user(): BelongsTo { return $this->belongsTo(User::class); }DB::table("orders")->where("status", "paid")->get();DB::transaction(function () {
// database operations
});return response()->json(["id" => $order->id], 201);Order::where("user_id", $user->id)->orderBy("id")->paginate(20);SELECT id, name FROM users;INSERT INTO orders (user_id, total_cents, status) VALUES (?, ?, ?);UPDATE orders SET status = ? WHERE id = ? AND status = ?;DELETE FROM orders WHERE id = ?;WHERE user_id = ? AND status IN (?, ?)SELECT o.id, u.name
FROM orders o JOIN users u ON u.id = o.user_id;SELECT user_id, SUM(total_cents) FROM orders GROUP BY user_id;ORDER BY created_at DESC, id DESCSELECT id FROM orders ORDER BY id LIMIT 20 OFFSET 40;BEGIN;
-- writes
COMMIT;
-- On failure: ROLLBACK;GET /orders // read
POST /orders // create/action
PUT /orders/42 // replace
PATCH /orders/42 // partial update
DELETE /orders/42 // delete200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
422 Unprocessable Content
429 Too Many Requests
500 Internal Server Error// Bad:
DB::select("SELECT * FROM users WHERE id = $id");
// Good:
DB::select("SELECT * FROM users WHERE id = ?", [$id]);
// Preferred:
User::whereKey($id)->firstOrFail();{{-- Bad for untrusted content: {!! $comment !!} --}}
{{-- Good: --}}
{{ $comment }}<form method="post" action="/orders">
@csrf
<!-- fields -->
</form>// Bad: md5($password) or plaintext
// Good:
$hash = password_hash($password, PASSWORD_DEFAULT);
$valid = password_verify($password, $hash);// Bad:
$user->update($request->all());
// Good:
$user->update($request->safe()->only(["name", "email"]));$amountInCents = 1250; // USD 12.50
// Avoid careless financial arithmetic with $amount = 12.50;UPDATE accounts SET balance_cents = ?, version = version + 1
WHERE id = ? AND version = ?;// PostgreSQL/MySQL transactional engine, not SQLite row locking:
Account::whereKey($id)->lockForUpdate()->firstOrFail();