show user via their profile slug

In my project I work with slugs to display posts, etc…

I do it this way and it works fine:

class Post extends Model
    use HasFactory;

    public function getRouteKeyName()
        return 'slug';


Route::get('/{post}', [PublicPostController::class, 'show'])->name('');

The problem comes now when I want to show a user through the slug, but the slug is not in the users table, but in the profile table.

Schema::create('profiles', function (Blueprint $table) {
            $table->enum('privacity', [Profile::PUBLICO, Profile::PRIVADO])->default(Profile::PUBLICO);


This is where I’m lost and I don’t know how to approach it.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could define an accessor for this in your User model:

protected $appends = ['slug'];

protected $with = ['profile'];

public function getSlugAttribute($value): string
    return $this->profile->slug;

Method 2

You need to make a relationship between the user and profile page (Profile Belongs To User), then you retrive the user via the slug.

or if you want a simple way without relationship which i dont recommend:

//Get the profile from the request Slug.

$retriveProfile = Profile::where('slug',$request->slug)->firstOrFail();

//Get the user from the Profile we got of the slug.

$user = User::findOrFail($retriveProfile->user_id);

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x