laravel / tinker

Powerful REPL for the Laravel framework.
https://laravel.com/docs/artisan#tinker
MIT License
7.32k stars 130 forks source link

Models don't display hidden/appended attributes #122

Closed dshafik closed 3 years ago

dshafik commented 3 years ago

When displaying a models attributes, items added with $append are not displayed.

This is because $get->attributes() (here) doesn't return them.

The only sane way I can think to do this is to iterate over the appends array and add them to the $appends array before iterating for the results.

Here's a patch that will show the appended elements, as well as fixes what looks to be a minor bug in that it only showed visible attributes before — highlighting visible/hidden/appended differently:

diff --git a/src/TinkerCaster.php b/src/TinkerCaster.php
--- a/src/TinkerCaster.php  (date 1613706042053)
+++ b/src/TinkerCaster.php  (date 1613706042053)
@@ -109,11 +109,33 @@
         $visible = array_flip(
             $model->getVisible() ?: array_diff(array_keys($attributes), $model->getHidden())
         );
+        $hidden = array_flip($model->getHidden());
+
+        $appends = (function() {
+            return array_combine($this->appends, $this->appends);
+        })->bindTo($model, $model)();
+        foreach ($appends as $appended) {
+            $attributes[$appended] = $model->{$appended};
+        }

         $results = [];

-        foreach (array_intersect_key($attributes, $visible) as $key => $value) {
-            $results[(isset($visible[$key]) ? Caster::PREFIX_VIRTUAL : Caster::PREFIX_PROTECTED).$key] = $value;
+        foreach ($attributes as $key => $value) {
+            $prefix = '';
+
+            if (isset($visible[$key])) {
+                $prefix = Caster::PREFIX_VIRTUAL;
+            }
+
+            if (isset($hidden[$key])) {
+                $prefix = Caster::PREFIX_PROTECTED;
+            }
+
+            $results[$prefix.$key] = $value;
         }

         return $results;

This output for a standard User model (faker data, with UUID keys), which hides password and remember_token attributes, and also has an is_deleted attribute appended:

image

(Apologies for not submitting a PR, I couldn't figure out which branch to best use)

driesvints commented 3 years ago

Hi @dshafik. That all looks good to me. You can PR that to the 2.x branch which is the current stable branch. Thanks!