Lumen by Example - Lesson 5

Lumen by Example - Lesson 5

Lumen Backend Tutorial - 5 More Advanced Examples

Each example consists of around 200 lines of code, and explanations are broken into 5 points (each around 30 words).


Example 1: Webhook Listener API

Receives and processes incoming webhooks from third-party services.

File: routes/web.php

$router->post('/webhook', 'WebhookController@handle');

File: app/Http/Controllers/WebhookController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller {
    public function handle(Request $request) {
        Log::info('Webhook received', $request->all());

        return response()->json(['message' => 'Webhook processed'], 200);
    }
}

Explanation:

  1. Receives webhook requests from third-party services like Stripe, PayPal, or GitHub.

  2. Logs incoming data payloads for debugging and monitoring webhook events.

  3. Processes and responds with 200 OK to acknowledge receipt.

  4. Allows automated workflows, e.g., handling payments or Git actions.

  5. Essential for integrating external APIs that trigger real-time updates.


Example 2: Email Verification API

File: routes/web.php

$router->post('/register', 'AuthController@register');
$router->get('/verify-email/{token}', 'AuthController@verifyEmail');

File: app/Http/Controllers/AuthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Models\User;
use Illuminate\Support\Str;

class AuthController extends Controller {
    public function register(Request $request) {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'verification_token' => Str::random(60)
        ]);

        Mail::raw("Verify your email: /verify-email/{$user->verification_token}", function ($message) use ($user) {
            $message->to($user->email)->subject("Email Verification");
        });

        return response()->json(['message' => 'Verification email sent']);
    }

    public function verifyEmail($token) {
        $user = User::where('verification_token', $token)->first();
        if (!$user) {
            return response()->json(['error' => 'Invalid token'], 400);
        }

        $user->email_verified_at = now();
        $user->verification_token = null;
        $user->save();

        return response()->json(['message' => 'Email verified']);
    }
}

Explanation:

  1. Sends an email verification link after user registration.

  2. The verification token is stored in the database and linked to the user.

  3. Clicking the link verifies the email and clears the token.

  4. Ensures valid email accounts, reducing spam and fake users.

  5. Useful for account security, authentication, and user validation.


Example 3: Soft Delete API (Recoverable Data)

Allows "soft deleting" records instead of permanently deleting them.

File: routes/web.php

$router->delete('/posts/{id}', 'PostController@destroy');
$router->get('/posts/deleted', 'PostController@deletedPosts');
$router->post('/posts/{id}/restore', 'PostController@restore');

File: app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {
    use SoftDeletes;
    protected $fillable = ['title', 'content'];
}

File: app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller {
    public function destroy($id) {
        Post::findOrFail($id)->delete();
        return response()->json(['message' => 'Post soft deleted']);
    }

    public function deletedPosts() {
        return response()->json(Post::onlyTrashed()->get());
    }

    public function restore($id) {
        Post::withTrashed()->where('id', $id)->restore();
        return response()->json(['message' => 'Post restored']);
    }
}

Explanation:

  1. Uses soft deletes, marking records as deleted instead of removing them permanently.

  2. Users can restore deleted data instead of losing it forever.

  3. The onlyTrashed() method lists deleted records for recovery.

  4. Prevents accidental data loss, allowing easy restoration.

  5. Ideal for content management systems (CMS), blogs, and e-commerce.


Example 4: Dynamic Configuration API

Allows updating application settings via an API.

File: routes/web.php

$router->get('/settings', 'SettingsController@getSettings');
$router->post('/settings', 'SettingsController@updateSettings');

File: app/Models/Setting.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model {
    protected $fillable = ['key', 'value'];
}

File: app/Http/Controllers/SettingsController.php

<?php

namespace App\Http\Controllers;

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

class SettingsController extends Controller {
    public function getSettings() {
        return response()->json(Setting::pluck('value', 'key'));
    }

    public function updateSettings(Request $request) {
        foreach ($request->all() as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => $value]);
        }
        return response()->json(['message' => 'Settings updated']);
    }
}

Explanation:

  1. Stores application settings dynamically in the database instead of using static .env files.

  2. Enables real-time configuration updates via API, without restarting the application.

  3. Uses updateOrCreate() to update existing settings or create new ones.

  4. Retrieves settings in a key-value format for easy access.

  5. Useful for SaaS platforms, admin dashboards, and multi-tenant applications.


Example 5: Redis Caching API

Caches frequently requested API responses for better performance.

File: routes/web.php

$router->get('/products', 'ProductController@index');

File: app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\Product;

class ProductController extends Controller {
    public function index() {
        $products = Cache::remember('products', 60, function () {
            return Product::all();
        });

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

Explanation:

  1. Uses Redis caching to store and retrieve API responses efficiently.

  2. The Cache::remember() method caches results for 60 seconds before refreshing.

  3. Improves performance by reducing database queries for frequent requests.

  4. Prevents server overload, making the API more scalable.

  5. Useful for product catalogs, analytics dashboards, and high-traffic APIs.


Summary:

These examples introduce webhook listeners, email verification, soft deletes, dynamic settings, and Redis caching, demonstrating advanced Lumen backend techniques for performance and scalability.