
- Views: 767
- Category: Laravel
- Published at: 02 Sep, 2023
- Updated at: 03 Sep, 2023
What is Middleware in Laravel 10 and How to Create Middleware in Laravel 10
Middleware is an essential concept in web development that acts like a series of filtering mechanisms, standing between a request and a response. They are the unsung heroes that perform crucial tasks such as authentication, logging, CORS, and even SEO manipulations. In Laravel, middleware brings a whole new level of simplicity and functionality, making it easier for developers to insert layers of logic around HTTP requests and responses. Laravel 10 continues this legacy by providing an even more seamless way to implement middleware. In this blog post, we'll explore why middleware is so important in Laravel 10, and we'll take a deep dive into creating a custom middleware for SEO injection.
Why Middleware is Important in Laravel 10
In Laravel 10, middleware continues to play an indispensable role. Whether you need to verify a user's authentication status, restrict routes based on roles, or perform some task before or after the request lifecycle, middleware has got you covered. Laravel 10 enhances the middleware functionalities, making it more efficient and developer-friendly. With features like middleware priority and terminable middleware, Laravel 10 allows for more fine-grained control over the request lifecycle.
Understanding Middleware in Laravel 10
In Laravel 10, middleware are PHP classes that can be assigned to specific routes or globally across all routes. They contain a handle
The method that takes a $request
and a $next
closure. The $request
object contains information about the incoming HTTP request and the $next
closure allows the request to proceed to the next layer in the application.
Creating SEOInjection Middleware with Artisan
To create a middleware in Laravel, we use the Artisan command. For our SEOInjection middleware, the command would be:
php artisan make:middleware SEOInjection
This will create a new file SEOInjection.php in the app/Http/Middleware
<?php
namespace App\Http\Middleware;
use App\Models\SEO;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class SEOInjection
{
public function handle(Request $request, Closure $next): Response
{
$url = rtrim($request->getUri(), '/');
$url = str_replace('/public', '', $url);
$seo = SEO::query()
->where('page_url', $url)
->orWhere('old_page_url', $url)
->first();
if (!$seo) {
return $next($request);
}
if ($seo->old_page_url == $url) {
return redirect($seo->page_url, 301);
}
view()->share('seo', $seo);
return $next($request);
}
}
Step 2: Creating the Controller
Let's assume you have a controller named YourController. Add the following method to handle the upload route:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourController extends Controller
{
public function upload(Request $request)
{
// Your upload logic here
}
}
Step 3: Defining Routes
Single Route
To apply the middleware to a single route:
Route::post('/url/abc/xyz', [YourController::class, 'upload'])
->name('ckeditor.upload')
->middleware(['auth', 'role:admin', 'verified', 'SEOInjection']);
Group Route
Route::middleware(['auth', 'role:admin', 'verified', 'SEOInjection'])
->group(function () {
// Your routes here
});
Entire Website
$middleware array in app/Http/Kernel.php:
protected $middleware = [
// ...
\App\Http\Middleware\SEOInjection::class,
];
You've already provided the view logic for SEO. Place this logic inside the <head> tag of your HTML layout or specific view files:
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>{{ isset($seo) ? $seo->title : 'Shekz Tech' }}</title>
<meta name="description" content="{{ isset($seo) ? $seo->meta_description : 'Default Description' }}">
<meta name="keywords" content="{{ isset($seo) ? $seo->meta_keywords : '' }}">
@if(isset($seo) && $seo->canonical_url)
<link rel="canonical" href="{{ $seo->canonical_url }}"/>
@endif
<meta name="robots" content="{{ isset($seo) && $seo->robots ? $seo->robots : 'index' }}">
<link rel="alternate" hreflang="{{ isset($seo) ? $seo->hreflang : 'en' }}" href="{{ isset($seo) && $seo->page_url ? url($seo->page_url) : url()->current() }}">
@if(isset($seo))
<meta property="og:title" content="{{ isset($seo->og_tags['title']) && $seo->og_tags['title'] ? $seo->og_tags['title'] : $seo->title }}">
<meta property="og:description" content="{{ isset($seo->og_tags['description']) && $seo->og_tags['description'] ? $seo->og_tags['description'] : $seo->meta_description }}">
<meta property="og:image" content="{{ isset($seo->og_tags['image']) ? asset('storage/app/public/images/' . $seo->og_tags['image']) : asset('storage/app/public/images/ogdefault.png') }}">
<meta name="twitter:title" content="{{ isset($seo->twitter_tags['title']) && $seo->twitter_tags['title'] ? $seo->twitter_tags['title'] : $seo->title }}">
<meta name="twitter:description" content="{{ isset($seo->twitter_tags['description']) && $seo->twitter_tags['description'] ? $seo->twitter_tags['description'] : $seo->meta_description }}">
<meta name="twitter:image" content="{{ isset($seo->twitter_tags['image']) ? asset('storage/app/public/images/' . $seo->twitter_tags['image']) : asset('storage/app/public/images/ogdefault.png') }}">
@endif
Conclusion
We've walked through the entire process of setting up a middleware in Laravel 10 to handle SEO injections dynamically. The middleware fetches SEO data and shares it with the views, allowing for the dynamic generation of meta tags. We've also covered how to apply this middleware to single routes, groups of routes, and the entire website.
By following these steps, you can effectively manage SEO and other cross-cutting concerns in your Laravel 10 application. Middleware offers a powerful and flexible way to augment your application's behavior without modifying the core logic, making your codebase cleaner and more maintainable.
- Tag
- Laravel 10
- Middleware
0 Comment(s)