Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to remove specific unwanted symbols (%20) to create user friendly url using Str::slug in laravel

Converts the original title "My First Post" into a URL-friendly slug "my-first-post,"
Remove unwanted symbol from url like %20

Converts the original title "My First Post" into a URL-friendly slug "my-first-post,"

Two Approaches
str::slug
str_replace

use Illuminate\Support\Str;

// Original string
$title = "My First Post";

// Generate a slug
$slug = Str::slug($title);**

// Output: "my-first-post"
Enter fullscreen mode Exit fullscreen mode

In this example, the Str::slug method converts the original title "My First Post" into a URL-friendly slug "my-first-post," which can be used as part of a URL or as a unique identifier for the post.

In Laravel, Str::slug is a convenient utility for creating slugs, and it helps ensure that your slugs are standardized, safe for URLs, and compatible with various web browsers and platforms. It also handles special characters, spaces, and diacritics (e.g., accented letters) intelligently, making it a valuable tool for web development in Laravel.
Remove unwanted symbol from url like %20

<a class="nav-link active" href="{{ url('influencer-dashboard/' . Str::slug(Auth::user()->name)) }}">
    <div class="mx-auto mt-2" style="width: 350px;"> <!-- Centered div with fixed width -->
        <!-- Content -->
    </div>
</a>
Enter fullscreen mode Exit fullscreen mode
use Illuminate\Support\Str;

// Input URL with unwanted symbol
$url = "example.com/my%20page";

// Remove unwanted symbols
$cleanedUrl = str_replace('%20', '', $url);

// Generate a slug from the cleaned URL
$slug = Str::slug($cleanedUrl);

// Output: "my-page"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)