Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor

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


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".
    ->select(['', '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']);

Snippets by

PostSrc poster


Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets