Web Development by Solarise

Solarise.dev

Laravel SEO – Are You Doing Enough To Optimise Laravel For Search?

Laravel is an extremely powerful framework for building applications and websites. Techniques for implementing SEO are constantly evolving.

Laravel has so much potential for powerful SEO

Laravel is a well-regarded framework among PHP developers and offers a solid platform to build on. I’m a freelance Laravel developer from Edinburgh, Scotland with years of experience working with SEO and I’ve put together these useful tips for getting the most out of SEO in your Laravel installation.

The Challenges Of Laravel Search Engine Optimisation

Dynamic Content

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.

1. Consider Your URL Structures

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.

Here’s some good examples of SEO-performant URLs

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

And here’s some not-so-great examples to avoid

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.

2. Improve Your Page Speed

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.

3. Optimise Your Code Structure

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:

  • User Profile: https://example.com/users/jane-doe
  • Jane’s Articles: https://example.com/users/jane-doe/articles
  • A Specific Article: https://example.com/articles/the-laravel-journey
  • Articles with a Specific Tag: 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.

Model 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'];
}

Controller Logic

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'));
}

Display in Views

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.

4. Check Out These 3 Laravel SEO Libraries

Get a quick SEO head-start by installing one of these external tools in your Laravel app

spatie/laravel-seo-tools

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

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/laravel-meta-tags

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') }}">

5. Use Middleware To Boost Laravel’s SEO Performance

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.

Middleware for Multi-lingual Sites

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);
    }
}

Middleware For Trailing Slashes

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);
    }
}

Middleware For Noindex

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.

Mastering SEO in Laravel – A Holistic Approach

Laravel stands out as a robust framework, offering flexibility and scalability. However, ensuring that search engines respect and acknowledge your Laravel SEO efforts requires a blend of strategic planning, leveraging the right tools, and understanding the intricacies of the framework itself.
Author Image

About Robin Metcalfe

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.

Get in touch

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!

Please enable JavaScript in your browser to complete this form.

Solarise.dev Services

Maintenance Retainers

Min 3 hours per month, no contract

Project Planning

Get in touch to discuss your project details

Consultancy

Face-to-face chats. Solve your problems!