Search code examples
phplaravellaravel-jetstream

Get user profile photo for each message


I need to display each user's unique photo in a chat room. Laravel Jetstream

Getting user message

 {{ message.message}}

Initially I had, but realized it only gets the photo for the current logged in user.

:src="$page.props.user.profile_photo_url

I need to define a has one relationship and call something like:

Get user id which lines up with the user account

 {{ message.user_id}}

Then get the profile photo location from user table column but I can't seem to get it working

 {{ user->where('id','=',message.user_id)->value(photo_location) }}

Solution

  • The last line of your code is incorrect, but I don't think it needs to be fixed because what you did is a very bad practice when it comes to querying data.

    Let's say you display 50 message in a page. In this case, you have to make 50 extra queries to fetch user fotos. This will kill your app's performance. That's why you need to attach user's data to the messages. All you need is the following addition to the controller.

    $messages = Message::with('user')->...->get();
    

    If users table has a foreign key to profile photo, your query should be:

    $messages = Message::with('user.relation_name')->...->get();
    

    In the blade, you will have all user's data you need, and use it like

    {{ message->user->profile_photo_url }}
    

    To make this work, you will need one-to-many relationship between User and Message models, and I assume you have it already. If you don't check the docs. It's quite easy.

    **********/EDIT/

    Relationships

    Chat Message Model

    public function user(){
        return $this->hasOne('App\Models\ChatRoom','id','user_id');
    }
    

    Message Controller

        $messages= ChatMessage::where('chat_room_id','=',$roomId)
        ->with('user')
        ->orderBy('created_at','DESC')
        ->get();
    

    Then in the vue trying to test and get user id for the message, doesn't work

    {{ message.user.id }}