1

I'm attempting to access a models attributes by an array of keys. The desired functionality would work something like $model->getAttribute('name'), but accept an array instead of a string.

Let's say we had a model with attributes name of 'A', age of 2 and blood_type of 'B'.

$attributesToPull = ['name', 'age'];
$model->getAttributes($attributesToPull);

// returns ['A', 2]

I've checked through the Laravel docs and cant find anything that quite fits.

The results dont need to come straight from the model, they can be pulled into their own associative array using $model->getAttributes() and then have a native PHP array function such as array_intersect to filter the results, but even then I can't seem to find a function that will allow me to filter an associative array with an indexed array.

Does anyone know how I could go about this, ideally without using a loop or a callback? The answer can be pretty open, it can return a collection or an array and use either the associative array of the model attributes or call a function on the model itself.

1 Answer 1

4

The Model has a only method:

$model->only($attributesToPull);
Sign up to request clarification or add additional context in comments.

1 Comment

oh my god I knew there was something! haha. I've used that function before and totally forgot about it, I've been searching the docs for keys or attributes. I hope no future employers see this!

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.