Francisunoxx
Francisunoxx

Reputation: 1458

How to get current comment for selected documents with the same id?

I wanted to get the current comment for the document that selected. But the problem is. In my tables comments I have the same document_id. I just wanted to get the comment for the selected documents.

I'm thinking should I make my document_id unique? For me able to get the comment for one document. Still don't have idea how can I retrieve the comment for selected documents.

DB

DocumentController:

This is where I retrieve the document selected also the comment. As you can see here I retrieve the document that selected in my sent_document_user table with comments table. But when I tried to retrieve the comments based on selected documents. It takes all the comment in my database. I don't know where part I'm getting the error.

public function readSentDocuments($id)
{

    $documentLists = DB::table('sent_document_user')->select('documents.title', 'categories.category_type', 'documents.content', 'documents.id')
    ->join('documents', 'documents.id', '=', 'sent_document_user.document_id')
    ->join('categories', 'categories.id', '=', 'documents.category_id')->first();

    $commentLists = DB::table('comments')
    ->select('comments.comment_content', 'users.username', 'comments.id')
    ->join('users', 'users.id', '=', 'comments.commentBy')->get();

    return view ('document.readSent')->with('documentLists', $documentLists)->with('commentLists', $commentLists);

}

This is all the list document where the user has an option to choose.

public function showSentDocuments()
{

    $documentSent = DB::table('receive_document_user')->select('documents.title', 'documents.content', 'categories.category_type', 'users.username', 'receive_document_user.dateReceived', 'documents.id')
        //Table name     //PK                  //FK
        ->join('users', 'users.id', '=', 'receive_document_user.user_id')
        ->join('documents', 'documents.id', '=', 'receive_document_user.document_id')
        ->join('categories', 'categories.id', '=', 'documents.category_id')
        ->where('sender_id', '=', Auth::id())->get();

    return view ('document.sent')->with('documentSent', $documentSent);
}

CommentController

This is where saving or inserting of comments happen.

class CommentController extends Controller
{

public function postComments(Request $request, Document $id)
{

    $this->validate($request,
    [
        'comment' => 'required',
    ]);



    $commentObject = new Comment();

    $user = Auth::user();

    $commentObject->comment = $request->comment;
    $commentObject->sender_id = $user->id;

        //Obtaining the instance of relationship. The save method will automatically add the appropriate comment_id and sender_id value to the new Comment model.
    $id->comments()->save($commentObject);


    return redirect()->back();
}
}

View

<div class = "col-md-6">

    <form class = "form-vertical">

        <div class = "form-group">

            <div class="panel panel-default">

                <div class="panel-heading">Comments</div>

                @foreach ($commentLists as $list)
                    <div class="panel-body">
                        <p>{{ $list->comment }}</p>
                        <strong>Comment by:</strong>
                        <p>{{ $list->username }}</p>
                        <button type = "submit" class = "btn btn-primary">Reply</button>
                    </div>
                @endforeach

            </div>       

        </div>

    </form>

</div>

Models

Comment

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $tables = 'comments';

    protected $fillable =
    [
        'comment_content',
    ];


    public function documents()
    {
        return $this->belongsTo('App\Models\Document');
    }

    public function users()
    {
        return $this->belongsTo('App\Models\Comment');
    }
}

Document

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{

    protected $table = 'documents';

    protected $fillable = 
    [
        'title',
        'content',
        'category_id',
    ];


    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
}

User

<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class User extends Model implements AuthenticatableContract
{
    use Authenticatable;

    public function comments()
{
    return $this->hasMany('App\Models\Comment');
}
}

Migration

documents

public function up()
{
    Schema::create('documents', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('content');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });
}

users

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('middle_name');
        $table->string('email');
        $table->string('username');
        $table->string('address');
        $table->string('password');
        $table->string('remember_token');

        $table->integer('role_permission_id')->unsigned();

        $table->foreign('role_permission_id')->references('id')->on('roles_permissions_dt')->onDelete('cascade');
        $table->timestamps();
    });
}

Upvotes: 4

Views: 343

Answers (3)

I Made Pustikayasa
I Made Pustikayasa

Reputation: 126

@Francisunoxx My English not good but try to give you reference. you can filter by sender_id Assuming that sender_id same as user_id in app/User.php

// user has many comments
    public function comments()
    {
        return $this->hasMany('App\CommentsTable','by_user_id');
    }

then in app/Http/Controllers/UserController.php

 public function profile(Request $request, $id) 
  {
    $data['user'] = User::find($id);//find exist user_id

    $data['latest_comments'] = $data['user'] -> comments -> take(5);
    return view('admin.profile', $data);
  }

View for profile in resources/views/admin/profile.blade.php

       @foreach($latest_comments as $cmt)
            <p>{{ $cmt->comment_field }}</p>                
        @endforeach

i hope can help

Upvotes: 0

ishadif
ishadif

Reputation: 731

if you want to fetch all the related comments based on the selected document, you can leverage eloquent by defining your document model and comment model. I assume that relationship will be

//this is in your document model
public function comments() {
    return $this->hasMany(Comment::class);
}

so if you want to fetch all comments for some specific document :

//this is in your controller
$document = Document::find($id);
$document->comments()->get(); //getching all comments
//or
$document->comments; //either will work

then, you will loop that collection in your view.

Upvotes: 1

jaysingkar
jaysingkar

Reputation: 4435

Assuming that

  1. You are having unique id for each document in your document Model. i.e. the primary key for the Documents Table.
  2. You are having an unique id for each user in your User Model. i.e. the primary key for the Users Table.

So, your Models would have following methods to define relationship between them along with your other methods and attributes.

Document Model:

public function Comments(){
    return $this->hasMany('path_to_your_Comment_Model/Comment');
}

User Model:

//For using in first Approach Below
public function Comments($document_id){
    return $this->hasMany('path_to_your_Comment_Model/Comment')
                ->where('document_id',$document_id);
}
//For using in second Approach Below
public function Comments(){
    return $this->hasMany('path_to_your_Comment_Model/Comment');
}

Comment Model:

public function User(){
    return $this->belongsTo('path_to_your_User_Model/User');
}

public function Document(){
    return $this->belongsTo('path_to_your_Document_Model/Document');
}

Now to retrieve the Comments from the comments table for Document identified by document_id and the User identified by user_id, you can use the following code in your controller.

First Approach:

public function getComments(Request $request){
    $document_id = $request->document_id;//Retrieving document_id of selected document  
    $comments = Auth::User->user()->Comments($document_id)->get();
    // Your code to handle retrieved comments
}

Second Approach:

public function getComments(Request $request){
    $document_id = $request->document_id;//Retrieving document_id of selected document  

    $comments = Auth::User->user()->whereHas('comments',function($query) use($document_id){
                $query->where('document_id',$document_id);
                })
                ->get();
    // Your code to handle retrieved comments
}

Upvotes: 2

Related Questions