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:

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

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->id();
            $table->unsignedBigInteger('user_id');
            $table->string('slug')->unique();
            $table->text('biography')->nullable();
            $table->string('url')->nullable();
            $table->string('img_thumb')->nullable();
            $table->string('img_medium')->nullable();
            $table->string('img_large')->nullable();
            $table->enum('privacity', [Profile::PUBLICO, Profile::PRIVADO])->default(Profile::PUBLICO);
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->timestamps();
        });

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

Answers:

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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x