0

I'm using laravel package commentable by faustbrian. i've been getting the comment for a post using just like in documentation in github . I want to search the information for user who post the comment, e.g the user avatar, address, and other information as well. I want to include the user information (which is an array) to the current position index of array (while for each i push it). the problem is, i tried using array_push, array_merge and $data[$key]=>$value as well. but none of them is working when i dd the variable. please help.

public function notaPengurusan($id){
    $comments=Complaint::findOrFail($id)->comments->toArray();
    foreach ($comments as $comment){
        $creator=User::findOrFail($comment['creator_id'])->toArray();
        array_push($comment,$creator);
    }
    dd($comments);
    return view('complaint::notapengurusan',compact('comments'));
}

image when i dd the image this is simply as in commentable package but not user information

0

2 Answers 2

1

You need to use array index and its global variable $comments

foreach ($comments as $key=>$comment){
    $creator=User::findOrFail($comment['creator_id'])->toArray();
    array_push($comments[$key],$creator);
}
Sign up to request clarification or add additional context in comments.

Comments

0

you should add user() relationship in your Comment Model :

public function user(){
        return $this->belongsTo('App\Model\User','creator_id');
}

then no need to use for loop and finding user each time , use with('user'):

$comments=Comment::where(['post_id'=>$post_id])->with('user')->orderBy('created_at','desc')->paginate(12);

2 Comments

i'd thought about this as well but perhaps i simply dont want to meddle with the package model configuration. i'm pretty new to Laravel. Thank you.
If you project is for production , you shoud use relationship :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.