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.8K

3 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

Alaz

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 ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this