inertiajs / pingcrm

A demo application to illustrate how Inertia.js works.
http://demo.inertiajs.com
MIT License
2.14k stars 781 forks source link

refactor: improve user share in middleware #91

Closed innocenzi closed 3 years ago

innocenzi commented 4 years ago

This PR proposes to change the syntax of the user share to avoid repetition. The ternary always bugged me, and I think this is cleaner and more Laravel-ish.

return array_merge(parent::share($request), [
    'auth' => function () use ($request) {
        return [
            'user' => optional($request->user())->only('id', 'first_name', 'last_name', 'email', 'account')
        ];
    },
]);

This does not behave exactly the same as previously though: account here will share its timestamps, created_at and updated_at. I figured it wasn't a big deal in this case.

In PHP 8, and with arrow functions, this would be even cleaner:

return array_merge(parent::share($request), [
    'auth' => fn () => [
        'user' => $request->user()?->only('id', 'first_name', 'last_name', 'email', 'account')
    ];
]);

Slightly related: there was a role property, but it was always null (I think?) because there were no accessor for it and it's not a column. It's used as a scope, but an accessor like this would be required for the previous code to return a value for role:

// app/Models/User.php

public function getRoleAttribute()
{
    return $this->owner ? 'owner' : 'user';
}

I didn't add it and didn't add it in only either because it's not used in the Vue files.

reinink commented 3 years ago

Hey thanks for this @innocenzi, but I like the simplicity of the current implementation. 👍