Home / Snippets / Query belongsToMany Relationship with Specific Column Only in Laravel
Query belongsToMany Relationship with Specific Column Only in Laravel cover

Query belongsToMany Relationship with Specific Column Only in Laravel

1.6K

2 years ago

0 comments

If you want to query "belongsToMany" and only retrieve some specific columns, you can make use of the "select" statement method.

Define Columns in Select Method
Define the columns that you want to select after accessing the "belongsToMany" relation which in the example below is the "comments".
Post::first()
    ->comments()
    ->select(['comments.id', 'comments.title']);

Otherwise, if you want to retrieve the columns only for the current model then you place the "select" statement method right away.
Comment::select(['id', 'title'])->first()

Or if you prefer to use the "get" method.
Comment::where('id', 1)->get(['id', 'title']);
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this