Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

How to get the profile image in this case?

In a project I'm currently working on, there are many tables. There is specific table for user images. I want to display this image in the navbar. The navbar is in a file Navbar.blade.php. It has no controller or anything.

What would be a good practice to fetch the image data? Where should I SELECT from db? In the Navbar file itself? Or I should do something else?

Edit: This project is a mess. So there is no relationship between the users and their images. Should I create 2 models for Users and for Images (Since each has its own table), and make a relation ship between them? Then maybe use auth()->user->image?

Ty!

0 likes
5 replies
Snapey's avatar

Create an accessor method on the user model that returns a URL for the user's image, or a placeholder if no image.

You can then contain the messy logic of finding the right image within the User model and in the view change the img src like;

<img src="{{ Auth::user()->image }}" />

1 like
Ligonsker's avatar

@Snapey ty! will try. Btw before you answer, I already started creating a Model for the images table only and made a relationship between the User and the Photo. What do you think is a better idea? A relationship or an accessor? And why?

For an accessor in my case it would be something like:

public function getImage()
{
    return DB::table('images')->where('id', '=', Auth::user->id)->value('image_path');
}

// then use it with User->getImage();

versus using a relationship and then get the image path like so:

Auth::user()->UserImage->image_path
Snapey's avatar

@Ligonsker

Your relationship should be lower case, so I would expect

Auth::user()->userImage->image_path
1 like
Ligonsker's avatar

@Snapey Sorry, my mistake! it will be lower case. Are there any considerations that should make me choose one approach or another? maybe performance?

Which one would you prefer? The accessor or the relationship?

Snapey's avatar

@Ligonsker The only performance consideration would be if you listed all users with their images, in which case you would want to eager load the images to avoid n+1

If you load the image in the model then a database hit would occur, but if this is just one user then there is no difference in the number of queries.

1 like

Please or to participate in this conversation.