Posts Learn Components Snippets Categories Tags Tools new About
/

Query belongsToMany Relationship with Specific Column Only in Laravel

Learn how to query belongsToMany relationship and specify only the columns that want to be retrieved

Created on Jul 11, 2021

224 views

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']);

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

)