2

Laravel version 7.0, I am using cviebrock/eloquent-sluggable package.

What I want is to put @ as prefix to the username.

I included Sluggable trait in User model and set like this.

public function sluggable()
{
    return [
        'username' => [
            'source' => 'name',
            'separator' => '',
            'onUpdate' => true
        ]
    ];
}

Now what I want is https://mywebsite.com/@username url shows user profile.

I think either we can put @ as prefix in sluggable package or we can detect it in laravel route.

Can anyone suggest me better way?

Thank you

LoveCoding
  • 1,121
  • 2
  • 12
  • 33

2 Answers2

2

I would recommend you to try eloquent-sluggable's method and generate the prefixed slug there (i.e. in the @username format) instead of keeping @ as a part of the route.

The rationale behind this advice is that when you generate and store @ within the slug itself and not the route (as I understood you were questioning which one is better) you ease the task of referencing users with @ symbol as you only need to query matching entries and you do not need to care about making transformations (for example, to prefix the username with @ when generating a link) back and forth.

Update: added basic example for method to prefix with username with @

It is a basic example that shows how to prefix the user with @. Make sure to add spaces handling yourself in case usernames may contain those.

  return [
    'username' => [
      ...,
      'method' => function ($username, $separator) {
        // example from docs: strtolower(preg_replace('/[^a-z]+/i', $separator, $string));
        return "@{$username}";
      },
    ]
  ];
Vitaly Krenel
  • 43
  • 1
  • 5
0

I figured out the better solution.

I could add @ in laravel route easily.

Route::get('/@{username}', 'HomeController@user')->name('user.index');

We can save username without @ and put @ as prefix in laravel route.

Dharman
  • 30,962
  • 25
  • 85
  • 135
LoveCoding
  • 1,121
  • 2
  • 12
  • 33