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

cooperino's avatar

How to use Yajra DataTables with raw query and not model?

The docs show that you need a Model that corresponds to the DataTable:

    public function query(User $model)
    {
        return $model->newQuery();
    }

But what if I have some more complex query that is not a Model? For example:

    return $data = Auth::user()->select(//...)
        ->where(//...)
        ->where(\DB::raw(//...))
        ->leftJoin(//...)
        ->get();

How to make it work with Yajra?

0 likes
4 replies
cooperino's avatar

@MichalOravec But look the docs always return a model:

No But I was talking about something else. But I found it:

I just use

    public function dataTable($query)
    {
        return datatables()
            ->collection($query);
    }

instead of

    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)            
    }
MichalOravec's avatar
Level 75

@cooperino From the documentation....

$posts = Post::join('users', 'posts.user_id', '=', 'users.id')
    ->select(['posts.id', 'posts.title', 'users.name', 'users.email', 'posts.created_at', 'posts.updated_at']);

return Datatables::of($posts)->make(true);

Do you see ->get() there? No!

1 like
cooperino's avatar

@MichalOravec Ok that's a good way.

In my case specifically it had joins but sometimes you just get a raw query (not necessarily with joins), then I think the docs mention what I did - to use the collection method (So in my case I can use both, and now I will try your way as well)

Please or to participate in this conversation.