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 theDB
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!