-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[5.5] Add Model::only method #19459
[5.5] Add Model::only method #19459
Conversation
$results[$attribute] = $this->getAttribute($attribute); | ||
} | ||
|
||
return $results; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not use an array_map here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Used the same style as Request::only
public function only($keys) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@tillkruss array_map
won't work here because it's setting the key
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It could be done with array_flip
or array_combine
(which I prefer) though.
Dot notation would be cool, but more complex since we're also dealing with accessors. I'm willing to update the PR if there's interest. |
This change has been rejected before: #15748 Hopefully this does get merged in though, I find myself wanting it in new projects quite a lot! |
Regarding the previous PR feedback
An upside of having this on the model is that you could call |
$model = new EloquentModelStub;
// ...
$model->project = 'laravel';
// ...
$model->setHidden(['project']);
$this->assertEquals(['project' => 'laravel'], $model->only('project'));
// this test should have failed
$model = new EloquentModelStub;
// ...
$model->project = 'laravel';
// ...
$this->assertEquals(['project' => 'laravel', 'foo_bar' => null]], $model->only(['project', 'foo_bar']));
// this test should fail
$this->assertEquals(['project' => 'laravel']], $model->only(['project', 'foo_bar']));
// this test should pass Your function should only return: return Arr::only(
$this->attributesToArray(),
is_array($attributes) ? $attributes : func_get_args()
); |
@sebastiandedeyne - Needed this just yesterday! "what do you mean "->only" isn't defined???!!!" |
@lucasmichot I disagree on your first point. This is the perfect escape hatch for retrieving a serialiazed version of the model despite the visibility attributes. When calling |
Adds an
only
method to theModel
class that behaves likeRequest::only
, to quickly extract attributes from a model to an array.