Introduction
Today we want to introduce you to a new package we recently created. The package is called Laravel SEO Rewrite. Can you guess what its used for? Let's consider you have a Post Model, and you are going to write a post that has "My Amazing Blog Post" as a title. Now you have three options for dealing with that:
www.example.com/posts/1www.example.com/posts/My%20Amazing%20Blogpostwww.example.com/posts/my-amazing-blogpost
The third option is the way to go here. It's clearly more readable than the two other options, and it's also good for SEO. But what would happen if you have ranked this page on Google and you change the title (slug) of the post, and it isn't accessible through www.example.com/posts/my-amazing-blogpost, but instead through www.example.com/posts/my-super-blogpost?
If somebody clicks on the first link, they would get a "404 Page Not Found", which indicates to Google that this page doesn't exist anymore, and it gets removed from the index. But, that is not what you want! You want to keep the ranking and have a 301 Moved Permanently redirect to the new page. That is where our magic starts!
Installation
The installation of the package requires just two simple steps.
1.) Require package using composer
composer require black-bits/laravel-seo-rewrite
2.) Execute Migrations
php artisan migrate
Usage
In our package, we have a Service Provider class that automatically registers the middleware. The middleware checks before every request, to see if a given path is already registered as source, and redirects the user to the defined destination, if one exists.
To create a new redirect, simply create a new SeoRewrite entry:
The source value must be a relative path matching one of your routes. The destination can be any relative or absolute URL. The type must be a valid redirect type (permanent, temporary, etc.)
SeoRewrite::create([
'source' => '/old-route',
'destination' => '/new-route',
'type' => 301
]);
SeoRewrite::create([
'source' => '/old-route',
'destination' => 'https://your-new.domain/old-route',
'type' => 308
]);
We run a basic redirect loop detection on model save, but not all cases can be detected. Please be aware that you can potentially create loops.
Conclusion
With our package, you can easily manage rewrites, and don't have to worry about it again. We also have detection of rewrite loops, so if a loop occurs, you would get an exception.
If you have any ideas, feedback for improvement, please drop us a message or create an issue on our Github repository, so we can take a look at that. Also feel free to contribute.

