Laravel is an extremely powerful framework for building applications and websites. Techniques for implementing SEO are constantly evolving.
While Laravel excels at creating dynamic content, this can sometimes trip up search engine crawlers, especially if you’re building out complex relationships and custom page structures. It’s vital to make content both dynamic and accessible, but with some foresight and planning you can smooth this out.
Clean, descriptive URLs are the goal. When considering Laravel SEO best practices, crafting these requires a bit of finesse – think in advance about how you’re going to plan out your URL schemas for SEO performance.
Example 1: https://example.com/products/laptops/dell-xps-15
Great! The URL clearly indicates the page’s purpose and what we’re selling. Useful SEO keywords help target visitors.
Example 2: https://example.com/blog/2023/09/laravel-seo-tips
Superb! Organized by date, helping visitors easily understand when the content was published or refreshed. No unnecessary extra characters
Example 3: https://example.com/index.php?id=12345
Wow, not so hot. The URL is non-descriptive and gives no indication of the page’s content. Dynamic parameters like ?id=12345 are not SEO-friendly and can confuse users
Resourceful Routing: Laravel’s resourceful routing allows you to automatically map routes to controller actions, avoiding the need for query parameters like ?id=123
. Instead, you can have URLs like /articles/123
.
Route::resource('articles', 'ArticleController');
This will generate routes like articles/{article}
, where {article}
is a placeholder for the article’s ID.
Example 4: https://example.com/prod/cat/laptop/brand/dell
This is hard to read. Abbreviations like “prod” and “cat” are ambiguous and not SEO-friendly. The structure lacks a clear hierarchy, making it less intuitive for users.
Route Model Binding: With route model binding, you can type-hint a model in the route definition, and Laravel will automatically inject the corresponding model instance based on the ID or another field in the URL.
For example, in a route definition:
Route::get('articles/{article}', 'ArticleController@show');
And in the ArticleController
:
public function show(Article $article) {
return view('articles.show', compact('article'));
}
Here, Laravel will automatically fetch the Article
model that corresponds to the {article}
ID in the URL.
Laravel is efficient, but assets need optimization. Caching and swift server responses are crucial. Laravel SEO techniques often focus on the structural side of things but neglect the basics – making sure visitors see your content fast.
Like most ranking factors, page load time alone won’t earn you a top spot on the SERPs, but a slow speed will hold you back from ranking higher.
Neil Patel, NP Digital – “We Analyzed 143,827 URLs and Discovered the Overlooked Speed Factors That Impact Google Rankings”
Some often overlooked methods in Laravel to boost page speed are
Caching: Utilize Laravel’s caching system to cache views, routes, and config. This reduces the time taken to fetch data, especially from databases.
Asset Compilation: Use Laravel Mix to compile and minify assets like CSS, JavaScript, and images. This reduces the file size and number of requests. This will look something like this
mix.js('resources/js/app.js', 'public/js').minify('public/js/app.js');
mix.sass('resources/sass/app.scss', 'public/css').minify('public/css/app.css');
Database Optimization: Use Laravel’s Eloquent ORM efficiently. Avoid N+1 query problems by eager loading relationships. For example
$users = App\User::with('orders')->get();
Optimize Images: Use packages like spatie/laravel-image-optimizer
to automatically optimize images when they are saved in a specific directory.
HTTP/2: If your server supports it, enable HTTP/2. It allows multiple requests and responses to be multiplexed over a single connection, reducing latency.
Server-Side Improvements: Use PHP’s OPcache to cache compiled PHP bytecode, and consider using a reverse proxy like Varnish to cache full-page content.
To rank well after all your Laravel SEO optimisation efforts, you’ll need to have a well planned out front-end, and to achieve this your overall application structure should reflect this structure.
In Laravel, models and their relationships play a pivotal role in shaping the data structure of an application. Let’s delve into how these can be represented with intuitive URL structures.
Consider three models: User
, Article
, and Tag
. A user can write multiple articles, establishing a one-to-many relationship between User
and Article
. Meanwhile, articles can have multiple tags and vice versa, forming a many-to-many relationship between Article
and Tag
. Here’s how these relationships can be mapped in URLs:
https://example.com/users/jane-doe
https://example.com/users/jane-doe/articles
https://example.com/articles/the-laravel-journey
https://example.com/tags/laravel-tips
By structuring URLs this way, we create a clear, logical pathway for both users and search engines, enhancing navigation and Laravel SEO structure.
In the Article
model, we can have fields like meta_title
, meta_description
, and meta_keywords
to store Laravel’s SEO metadata.
class Article extends Model {
protected $fillable = ['title', 'content', 'meta_title', 'meta_description', 'meta_keywords'];
}
In the ArticleController
, when fetching an article, we can pass the SEO metadata to the view.
public function show(Article $article) {
return view('articles.show', compact('article'));
}
In the article’s view (e.g., articles.show.blade.php
), you can output the SEO metadata in the <head>
section.
<head>
<title>{{ $article->meta_title }}</title>
<meta name="description" content="{{ $article->meta_description }}">
<meta name="keywords" content="{{ $article->meta_keywords }}">
</head>
By integrating SEO metadata directly into the Article
model, we streamline the process of optimizing each article for search engines. This approach ensures that as content is created or updated, the corresponding SEO data can be easily managed and displayed.
Get a quick SEO head-start by installing one of these external tools in your Laravel app
Spatie’s Laravel SEO Tools package offers a fluent API to manage SEO data. From setting meta tags to generating canonical URLs, it’s a comprehensive solution for your Laravel application.
Installation via Composer is straightforward:
composer require spatie/laravel-seo-tools
And in your views, add the following tag to your header to output the necessary SEO front-end markup.
{!! seo_helper()->render() !!}
Model Configuration: Extend your model to include SEO fields like meta_title
, meta_description
, etc.
class Article extends Model {
protected $fillable = ['title', 'content', 'meta_title', 'meta_description'];
}
Admin Control: While the package doesn’t provide an out-of-the-box admin interface, you can easily integrate it with Laravel’s form system to manage these fields.
In your form:
<input type="text" name="meta_title" value="{{ old('meta_title', $article->meta_title) }}">
<textarea name="meta_description">{{ old('meta_description', $article->meta_description) }}</textarea>
Artesaos SEOTools provides an elegant way to define Laravel SEO metadata and OpenGraph data. It’s flexible and integrates seamlessly with Laravel.
Integration:
composer require artesaos/seotools
In your controller:
SEOMeta::setTitle('Home');
SEOMeta::setDescription('This is my page description');
You can take a similar approach to configuring your model’s fields to provide additional administrative control.
Torann’s Laravel Meta Tags is a straightforward tool for managing meta tags in your Laravel SEO configuration. It’s simple, effective, and perfect for those who want a no-fuss solution.
Integration:
composer require torann/laravel-meta-tags
In your views:
<meta name="title" content="{{ MetaTag::get('title') }}">
<meta name="description" content="{{ MetaTag::get('description') }}">
Middleware in Laravel acts as a filtering mechanism, processing HTTP requests before they hit your application. While commonly used for tasks like authentication, middleware can be a powerful tool for embedding Laravel SEO enhancements into your app’s execution flow.
Imagine you have a multi-lingual Laravel application. Search engines value content localization, and serving content in a user’s native language can significantly improve user experience and SEO rankings. With middleware, you can automatically set the application’s locale based on the user’s geographical location or browser settings. This ensures that users and search engines access content tailored to specific regions, boosting your site’s relevance in local search results.
namespace App\Http\Middleware;
use Closure;
use App;
class SetLocale {
public function handle($request, Closure $next) {
$location = $request->header('Country-Code'); // Assuming you have a way to get the country code.
if ($location == 'FR') {
App::setLocale('fr');
}
return $next($request);
}
}
Another Laravel SEO challenge is handling trailing slashes in URLs. While https://example.com/blog
and https://example.com/blog/
might look the same to us, search engines treat them as separate pages, leading to potential duplicate content issues. A simple middleware can ensure consistency by redirecting all requests to either the version with or without the trailing slash.
class HandleTrailingSlash {
public function handle($request, Closure $next) {
if (substr($request->getPathInfo(), -1) !== '/') {
return redirect($request->path() . '/');
}
return $next($request);
}
}
Lastly, consider the “noindex” directive for search engines, useful for pages you don’t want indexed (like admin panels or user settings). Instead of manually adding meta tags to specific views, a middleware can automatically insert the “noindex” meta tag for routes belonging to certain groups.
Incorporating middleware into your Laravel SEO strategy can automate and streamline many processes, ensuring a more consistent and efficient approach to search engine optimization. As with any tool, the key lies in understanding its potential and applying it effectively.
// Middleware
class NoIndexRoute {
public function handle($request, Closure $next) {
if ($request->is('dont-index-these/*')) {
view()->share('noindex', true);
}
return $next($request);
}
}
// view.blade.php
@if(isset($noindex))
<meta name="robots" content="noindex">
@endif
Remember to register these middlewares in app/Http/Kernel.php
to make them available for use.
Robin is the dedicated developer behind Solarise.dev. With years of experience in web development, he's committed to delivering high-quality solutions and ensuring websites run smoothly. Always eager to learn and adapt to the ever-changing digital landscape, Robin believes in the power of collaboration and sharing knowledge. Outside of coding, he enjoys diving into tech news and exploring new tools in the industry.
If you'd like to get in touch to discuss a project, or if you'd just like to ask a question, fill in the form below.
Send me a message and I'll get back to you as soon as possible. Ask me about anything - web development, project proposals or just say hi!