• Calculating...
  • 1 month ago
  • 256 Views

Sanitize and Create URLs via Laravel command

For both SEO and user experience, modern web application must have clear and readable URLs. Laravel 11 makes it easy to automate this process using custom Artisan commands. In this post, we'll walk through how to create a command that sanitizes text from a model and saves it as a URL.

 

Step-by-Step Guide to Creating the Command

 

1. Introduction to the Command

Our goal is to create a command that will fetch entries from a database, sanitize a specific text field, and save the sanitized version as a URL. This can be particularly useful for models like quotes, articles, or any content where you want to generate user-friendly URLs.

 

2. Define the Command

First, create a new Artisan command using the following command in your terminal:

php artisan make:command SanitizeAndCreateUrl

 

This will generate a new command class in the app/Console/Commands directory.

 

3. Command Structure

Next, let's define the structure of our command:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SanitizeAndCreateUrl extends Command
{
    protected $signature = 'sanitize:url';
    protected $description = 'Sanitize the text and save it as URL if URL is empty';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Fetch urls  from the model you have defined
        $your_model = DB::table('your_model')->whereNull('url')->get();

        foreach ($your_model as $given_model) {
            // Sanitize the text (change it as per the input)
            $sanitizedText = $this->sanitizeText($given_model->text);

            // Save the sanitized text as URL
            DB::table('your_model')
                ->where('id', $given_model->id)
                ->update(['url' => $sanitizedText]);

            $this->info("Updated model ID {$given_model->id} with URL: {$sanitizedText}");
        }

        $this->info('All texts have been processed.');
    }

    private function sanitizeText($text)
    {
        // Remove all non-alphanumeric characters except spaces
        $sanitizedText = preg_replace('/[^a-zA-Z0-9\s]/', '', $text);
        // Replace spaces with hyphens and convert to lowercase
        $sanitizedText = strtolower(trim(preg_replace('/\s+/', '-', $sanitizedText)));
        // Remove consecutive hyphens
        $sanitizedText = preg_replace('/-+/', '-', $sanitizedText);

        // Ensure the sanitized text is within 50 words
        $words = explode('-', $sanitizedText);
        if (count($words) > 10) {
            $sanitizedText = implode('-', array_slice($words, 0, 10));
        }

        // URL encode the sanitized text
        return urlencode($sanitizedText);
    }
}

 

4. Explanation of the Code

  • Namespace and Imports: The command is placed under the App\Console\Commands namespace. We import the necessary classes, including the DB facade for database operations.

  • Signature and Description: The $signature property defines the command's name (sanitize:url). The $description provides a brief explanation of what the command does.

  • Constructor: The __construct method initializes the command by calling the parent constructor.

  • Handle Method: This is the main method executed when the command runs. It fetches all quotes with a null URL, sanitizes the text, and saves the sanitized text as the URL.

  • Sanitize Text Method: This private method handles the text sanitization. It removes non-alphanumeric characters, replaces spaces with hyphens, converts the text to lowercase, removes consecutive hyphens, limits the URL to 50 words, and URL-encodes the final string.

 

5. Running the Command

To execute the command, run:

php artisan sanitize:url

 

This will process all relevant entries and update their URLs based on the sanitized text.

 

Conclusion

With custom Artisan commands, creating clean, user-friendly URLs automatically in Laravel is simple. You can make sure the URLs in your application are both readable and search engine optimised by following the preceding steps. Have fun with coding!

Share:

Related Post

CRUD Operations In Laravel 8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 8. Laravel is one of the fastest-growing frameworks for PHP.

  • 3 years ago

Scheduling Tasks with Cron Job in Laravel 5.8

Cron Job is used to schedule tasks that will be executed every so often. Crontab is a file that contains a list of scripts, By editing the Crontab, You can run the scripts periodically.

  • 5 years ago

Connecting Multiple Databases in Laravel 5.8

This tutorial is created to implement multiple database connections using mysql. Let’s see how to configure multiple database connections in Laravel 5.8.

  • 5 years ago

Integrating Google ReCaptcha in Laravel 5.8

reCAPTCHA is a free service from Google. It’s a CAPTCHA-like system designed to recognize that the user is human and, at the same time, assist in the digitization of books. It helps to protects your w

  • 5 years ago

Clearing Route, View, Config Cache in Laravel 5.8

Sometimes you may face an issue that the changes to the Laravel Project may not update on the web. This occures when the application is served by the cache. In this tutorial, You’ll learn to Clear App

  • 5 years ago