Laravel Framework & Artisan Cheat Sheet

Quick reference guide for Laravel: Artisan CLI commands, Eloquent ORM queries, Blade directives, and routing.

Languages
laravel
php
backend

Laravel is a web application framework with expressive, elegant syntax. It provides robust tools for routing, authentication, ORM database management, and queuing.

Essential `php artisan` CLI Commands

Table
CommandAction / Purpose
php artisan serveStart local PHP development server on http://127.0.0.1:8000
php artisan make:model Post -mcrCreate Model with Migration (-m), Controller (-c), Resource (-r)
php artisan migrateExecute pending database schema migrations
php artisan migrate:fresh --seedDrop all tables, re-run all migrations, and populate database seeders
php artisan route:listDisplay table of all registered HTTP routes
php artisan tinkerLaunch interactive REPL shell to test Eloquent queries and code
php artisan config:cacheCombine all configuration files into single cached file

Eloquent ORM & Query Builder Syntax

php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        // Eloquent query with eager loading (N+1 protection)
        $users = User::with('posts')
            ->where('active', true)
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return response()->json($users);
    }

    public function store(Request $request)
    {
        // Input validation
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
        ]);

        $user = User::create($validated);
        return response()->json($user, 201);
    }
}

Blade Template Directives

html
<!-- Control Flow -->
@if ($users->isEmpty())
    <p>No registered users found.</p>
@else
    <ul>
        @foreach ($users as $user)
            <li>{{ $user->name }} ({{ $user->email }})</li>
        @endforeach
    </ul>
@endif

<!-- Form CSRF Protection -->
<form method="POST" action="/profile">
    @csrf
    @method('PUT')
    <input type="text" name="name" value="{{ old('name') }}" />
    <button type="submit">Update</button>
</form>

Common Pitfalls & Tips

[!WARNING] Accessing un-loaded relationships inside loops causes the N+1 query problem! Always use User::with('relation') to eager-load relationships.

[!TIP] Always run php artisan config:clear after editing your .env file during local development.