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:
Receives webhook requests from third-party services like Stripe, PayPal, or GitHub.
Logs incoming data payloads for debugging and monitoring webhook events.
Processes and responds with 200 OK to acknowledge receipt.
Allows automated workflows, e.g., handling payments or Git actions.
Essential for integrating external APIs that trigger real-time updates.
Example 2: Email Verification API
Sends email verification links and verifies user email.
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:
Sends an email verification link after user registration.
The verification token is stored in the database and linked to the user.
Clicking the link verifies the email and clears the token.
Ensures valid email accounts, reducing spam and fake users.
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:
Uses soft deletes, marking records as deleted instead of removing them permanently.
Users can restore deleted data instead of losing it forever.
The
onlyTrashed()
method lists deleted records for recovery.Prevents accidental data loss, allowing easy restoration.
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:
Stores application settings dynamically in the database instead of using static
.env
files.Enables real-time configuration updates via API, without restarting the application.
Uses
updateOrCreate()
to update existing settings or create new ones.Retrieves settings in a key-value format for easy access.
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:
Uses Redis caching to store and retrieve API responses efficiently.
The
Cache::remember()
method caches results for 60 seconds before refreshing.Improves performance by reducing database queries for frequent requests.
Prevents server overload, making the API more scalable.
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.