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

DarkianZ's avatar

How to display username from user_id on show($id) method ?

Hi everyone, got a problem when trying to show the username of that specific user_id when displaying on front end. Im using react as front.

public function show($id) { $posts = Post::find($id); return response()->json([ 'status' => 200, 'posts' => $posts, ]); }

state = { post_title: '', post_content: '', user_id: '', } async componentDidMount() { const post_id = this.props.match.params.id; const res = await axios.get(http://127.0.0.1:8000/api/show-post/${post_id}); // const res = await axios.get('http://127.0.0.1:8000/api/posts'); // console.log(res); if (res.data.status === 200) { this.setState({ post_title: res.data.posts.post_title, post_content: res.data.posts.post_content, user_id: res.data.posts.user_id, }); } }

When trying to this.state.post_title and post_content works, but on user_id I want it to display username instead. Any information will be helpful

0 likes
1 reply
deansatch's avatar

You need to return the user relationship too.

   public function show($id)
    {
        $posts = Post::with('user')->whereId($id)->first();
        return response()->json(['status' => 200, 'posts' => $posts,]);
    }

Then you should have res.data.posts.user.name available.

The above assumes you have a user() relationship on your Post model:

 public function user()
 {
     return $this->belongsTo(User::class);
  }

Also, if you are only fetching one post with your query you should probably use $post rather than $posts

Please or to participate in this conversation.