@dejuan.watsica
Enabling SEO-friendly URLs in Laravel involves several best practices that help ensure your URLs are clean, readable, and optimized for search engines. Here's how you can achieve SEO-friendly URLs in your Laravel application:
Named routes make it easy to generate URLs or redirects in your Laravel application. This ensures URLs remain consistent and readable.
1
|
Route::get('/post/{id}', [PostController::class, 'show'])->name('post.show'); |
You can generate the URL for this route using:
1
|
$url = route('post.show', ['id' => 1]); |
Instead of using IDs directly in your URLs, consider using slugs. Slugs are typically more meaningful and user-friendly.
First, you need to generate a slug when saving a resource. You can use Laravel’s Str
helper:
1 2 3 4 |
use IlluminateSupportStr; $post->slug = Str::slug($post->title); $post->save(); |
Update your routes and controllers to use slugs:
1
|
Route::get('/post/{slug}', [PostController::class, 'show'])->name('post.show'); |
In your controller:
1 2 3 4 |
public function show($slug) { $post = Post::where('slug', $slug)->firstOrFail(); return view('post.show', compact('post')); } |
With route model binding, Laravel can automatically inject the model instance directly into your route. This makes routes cleaner.
1
|
Route::get('/post/{post:slug}', [PostController::class, 'show'])->name('post.show'); |
Now your controller method receives a Post
model instance directly:
1 2 3 |
public function show(Post $post) { return view('post.show', compact('post')); } |
.htaccess
File (For Apache)If you’re using Apache, you may need to ensure your .htaccess
file is set up to handle “pretty” URLs.
1 2 3 4 5 6 7 8 9 10 11 12 |
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Front Controller RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> |
Structure your routes using RESTful principles to ensure consistency and clarity.
1
|
Route::resource('posts', PostController::class); |
Use route caching in production to speed up the route registration process.
1
|
php artisan route:cache |
Where possible, avoid using URL query strings, as clean URLs are generally considered more user-friendly and SEO-friendly.
By following these guidelines, you can create clean, SEO-friendly URLs in your Laravel application that are both user-friendly and search engine optimized.