0

I may be missing something extremely trivial, but is it possible to retrieve specific columns/fields from models when grabbing a collection rather then returning the entire item's fields?

Here is my query:

$items = Items::where('visible', true)->take(10)->get();

This obviously returns each item in there entirety, including unique id's, and other fields i dont want to be fetched... how can i refine this query to just select specific fields from the models?

3 Answers 3

3

Laravel Query Builder get() function receives array of columns which you need to fetch.

$items = Items::where('visible', true)->take(10)->get(['column_1', 'column_2']);

Sign up to request clarification or add additional context in comments.

Comments

1

Use select() method to do this:

$items = Items::select(['column_1', 'column_2']'])->where('visible', true)->take(10)->get();

Source: Latavel Database Query Builder

Comments

0

Laravel Query Builder gives a huge flexibility to write this types of query. You can use select(), get(), all() methods.

Items::where('visible', true)->take(10)->get('col_1', 'col_2');

OR

Items::select('col_1', 'col_2')->where('visible', true)->take(10)->get();
Items::select(['col_1', 'col_2'])->where('visible', true)->take(10)->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.