webfuelcode's avatar

How to call data from two different model in a view

I have post reported page in admin dashboard. Trying to make a page where all reported post will be listed.

This is a forum project so thread, comment and reply can be reported. I have two model, Thread and Comment (for comments and replies).

Here I want to display latest 10 post from thread and comment reported in a single page.

Currently I have this function and do not get how to make it

public function reported()
    {
        $reported = Thread::where('reported', true)->latest()->paginate(10);
        $reportedcomments = Comment::where('reported', true)->latest()->paginate(10);
        $categories = Category::get();
        return view('admin.thread.reported', compact('reported', 'reportedcomments', 'categories'))->with('i', (request()->input('page', 1) - 1) * 10);
    }

How to make these appear in a limited number like 10 of all in a page and then the pagination. Not the 10 and 10, means total 20 from both models.

$reported = Thread::where('reported', true)->latest()->paginate(10);
$reportedcomments = Comment::where('reported', true)->latest()->paginate(10);
0 likes
2 replies
SilenceBringer's avatar

@webfuelcode you can try to do it with unions, but you need to make sure you have the same columns in select from both tables, like

$threads = Thread::where('reported', true)
    ->select([
        DB::raw(' "thread" as type'),
        'id',
        'created_at',
    ]);

$result = Comment::where('reported', true)
    ->select([
        DB::raw(' "comment" as type'),
        'id',
        'created_at',
    ])
    ->union($threads)
    ->latest()
    ->limit(10)
    ->get();
webfuelcode's avatar

@silencebringer I tried it but it shows no result. I do not get the use of DB::raw in my case.

My table structure is below.

My Thread table is:

..........................................................................................................

| id | user_id | category_id | subject | slug | body | reported |

..........................................................................................................

My Comment table is:

...................................................................................................................................

| id | user_id | body | commentable_id | commanetable_type | reported |

...................................................................................................................................

Please or to participate in this conversation.