Code Examples

Learn how to add syntax-highlighted code blocks, inline code, and command examples to your documentation.

Inline Code

Use single backticks for inline code references:

Use the `php artisan serve` command to start the server.
Configure your `APP_KEY` in the `.env` file.
The `User` model extends `Authenticatable`.

Rendered:

Use the php artisan serve command to start the server.
Configure your APP_KEY in the .env file.
The User model extends Authenticatable.

Code Blocks

Use triple backticks (```) for multi-line code:

```
function hello() {
    console.log('Hello, World!');
}
```

Rendered:

function hello() {
    console.log('Hello, World!');
}

Syntax Highlighting

Specify the language after the opening backticks:

PHP

```php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users.index', compact('users'));
    }
}
```

Rendered:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users.index', compact('users'));
    }
}

JavaScript

```javascript
async function fetchUsers() {
    const response = await fetch('/api/users');
    const data = await response.json();
    return data;
}

fetchUsers()
    .then(users => console.log(users))
    .catch(error => console.error('Error:', error));
```

Rendered:

async function fetchUsers() {
    const response = await fetch('/api/users');
    const data = await response.json();
    return data;
}

fetchUsers()
    .then(users => console.log(users))
    .catch(error => console.error('Error:', error));

HTML

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Page</title>
</head>
<body>
    <h1>Welcome</h1>
    <p>Hello, World!</p>
</body>
</html>
```

Rendered:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Page</title>
</head>
<body>
    <h1>Welcome</h1>
    <p>Hello, World!</p>
</body>
</html>

CSS

```css
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.button {
    background-color: #0366d6;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
    border: none;
    cursor: pointer;
}

.button:hover {
    background-color: #0256b7;
}
```

Rendered:

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.button {
    background-color: #0366d6;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
    border: none;
    cursor: pointer;
}

.button:hover {
    background-color: #0256b7;
}

SQL

```sql
CREATE TABLE users (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP NULL,
    PRIMARY KEY (id)
);

INSERT INTO users (name, email, password)
VALUES ('John Doe', '[email protected]', 'hashed_password');

SELECT * FROM users WHERE email = '[email protected]';
```

Rendered:

CREATE TABLE users (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP NULL,
    PRIMARY KEY (id)
);

INSERT INTO users (name, email, password)
VALUES ('John Doe', '[email protected]', 'hashed_password');

SELECT * FROM users WHERE email = '[email protected]';

JSON

```json
{
    "name": "My Application",
    "version": "1.0.0",
    "description": "A sample application",
    "dependencies": {
        "laravel": "^12.0",
        "vue": "^3.0"
    },
    "config": {
        "debug": true,
        "timezone": "UTC"
    }
}
```

Rendered:

{
    "name": "My Application",
    "version": "1.0.0",
    "description": "A sample application",
    "dependencies": {
        "laravel": "^12.0",
        "vue": "^3.0"
    },
    "config": {
        "debug": true,
        "timezone": "UTC"
    }
}

Bash/Shell

```bash
#!/bin/bash

# Install dependencies
composer install
npm install

# Setup environment
cp .env.example .env
php artisan key:generate

# Run migrations
php artisan migrate --seed

# Start server
php artisan serve
```

Rendered:

#!/bin/bash

# Install dependencies
composer install
npm install

# Setup environment
cp .env.example .env
php artisan key:generate

# Run migrations
php artisan migrate --seed

# Start server
php artisan serve

YAML

```yaml
name: CI Pipeline
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: php artisan test
```

Rendered:

name: CI Pipeline
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: php artisan test

Command Examples

Terminal Commands

Install the package:

```bash
composer require vendor/package

Run migrations:

php artisan migrate

Start development server:

npm run dev

### Command with Output

```markdown
Check PHP version:

```bash
php -v
```

Output:

```
PHP 8.2.15 (cli) (built: Jan 15 2024 12:30:45) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.2.15
```

Multi-line Commands

Use backslashes for line continuation:

docker run -d \
    --name myapp \
    -p 8000:8000 \
    -v $(pwd):/app \
    -e APP_ENV=production \
    myapp:latest

Code with Comments

Inline Comments

// Get all active users
$users = User::where('active', true)->get();

// Send welcome email
Mail::to($user)->send(new WelcomeEmail());

// Log the action
Log::info('User registered', ['user_id' => $user->id]);

Block Comments

/**
 * Fetch user data from API
 * @param {number} userId - The user ID to fetch
 * @returns {Promise} User data object
 */
async function getUser(userId) {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) {
        throw new Error('User not found');
    }
    return response.json();
}

Highlighted Lines

While not directly supported, use comments to indicate important lines:

<?php

namespace App\Http\Controllers;

class ApiController extends Controller
{
    public function store(Request $request)
    {
        // IMPORTANT: Validate input before processing
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users'
        ]);

        // Process the request
        $user = User::create($validated);

        return response()->json($user, 201);
    }
}

Code with Placeholders

Use uppercase placeholders for values users should replace:

# Clone repository
git clone https://github.com/YOUR-USERNAME/YOUR-REPO.git

# Configure database
DB_HOST=YOUR-DATABASE-HOST
DB_DATABASE=YOUR-DATABASE-NAME
DB_USERNAME=YOUR-DATABASE-USER
DB_PASSWORD=YOUR-DATABASE-PASSWORD

# Set API key
API_KEY=YOUR-API-KEY-HERE

API Request Examples

cURL

# GET request
curl -X GET "https://api.example.com/users" \
     -H "Authorization: Bearer YOUR-API-TOKEN" \
     -H "Accept: application/json"

# POST request
curl -X POST "https://api.example.com/users" \
     -H "Authorization: Bearer YOUR-API-TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "John Doe",
       "email": "[email protected]"
     }'

# PUT request
curl -X PUT "https://api.example.com/users/123" \
     -H "Authorization: Bearer YOUR-API-TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"name": "Jane Doe"}'

# DELETE request
curl -X DELETE "https://api.example.com/users/123" \
     -H "Authorization: Bearer YOUR-API-TOKEN"

JavaScript Fetch

// GET request
fetch('https://api.example.com/users', {
    headers: {
        'Authorization': 'Bearer YOUR-API-TOKEN',
        'Accept': 'application/json'
    }
})
.then(response => response.json())
.then(data => console.log(data));

// POST request
fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer YOUR-API-TOKEN',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'John Doe',
        email: '[email protected]'
    })
})
.then(response => response.json())
.then(data => console.log(data));

PHP

<?php

// GET request with Guzzle
$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api.example.com/users', [
    'headers' => [
        'Authorization' => 'Bearer YOUR-API-TOKEN',
        'Accept' => 'application/json'
    ]
]);

$data = json_decode($response->getBody(), true);

// POST request
$response = $client->request('POST', 'https://api.example.com/users', [
    'headers' => [
        'Authorization' => 'Bearer YOUR-API-TOKEN',
        'Content-Type' => 'application/json'
    ],
    'json' => [
        'name' => 'John Doe',
        'email' => '[email protected]'
    ]
]);

Configuration Files

.env Example

APP_NAME="My Application"
APP_ENV=production
APP_KEY=base64:RANDOM-KEY-HERE
APP_DEBUG=false
APP_URL=https://example.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=app_database
DB_USERNAME=app_user
DB_PASSWORD=secure_password

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Config File

<?php

return [
    'name' => env('APP_NAME', 'Laravel'),
    'env' => env('APP_ENV', 'production'),
    'debug' => (bool) env('APP_DEBUG', false),
    'url' => env('APP_URL', 'http://localhost'),
    
    'timezone' => 'UTC',
    'locale' => 'en',
    'fallback_locale' => 'en',
    
    'key' => env('APP_KEY'),
    'cipher' => 'AES-256-CBC',
];

Best Practices

1. Always Specify Language

Good:
```php
<?php echo "Hello"; ?>

Avoid:

<?php echo "Hello"; ?>

### 2. Keep Code Readable

- Use proper indentation
- Add comments for complex logic
- Break long lines appropriately
- Remove unnecessary code

### 3. Include Context

```markdown
Update the user's email address:

```php
$user = User::find($id);
$user->email = $request->email;
$user->save();
```

This will trigger the email verification workflow.

4. Show Complete Examples

Include all necessary imports and setup:

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function update(Request $request, User $user)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $user->id
        ]);

        $user->update($validated);

        return redirect()->route('users.show', $user)
            ->with('success', 'User updated successfully!');
    }
}

5. Test Your Code

Supported Languages

Common languages for syntax highlighting:

  • php - PHP
  • javascript / js - JavaScript
  • typescript / ts - TypeScript
  • python - Python
  • ruby - Ruby
  • java - Java
  • csharp / cs - C#
  • cpp - C++
  • go - Go
  • rust - Rust
  • html - HTML
  • css - CSS
  • scss - SCSS/Sass
  • sql - SQL
  • bash / shell - Bash/Shell
  • json - JSON
  • yaml / yml - YAML
  • xml - XML
  • markdown / md - Markdown
  • diff - Diff
  • docker - Dockerfile

Next Steps

×